初尝nestjs,回味不穷【第一章】

背景

闲来无事,勾栏听曲。难得有时间,那就学习学习吧!作为前端而言会一种node框架就行了额,但是我发现eggjs已经很久没有更新了,所以想重新学习一种node框架,在各种筛选下我选择了nestjs。
我们就开始学习吧!铛铛铛。。。好朋友走起!!!

创建项目

第一步: 肯定是先安装nestjs了,然后在根据nestjs进行创建项目,如下代码示例。当然你也可以根据官网一步一步的进行开发。nestjs中文官网

npm i -g @nestjs/cli
nest new project-name

创建项目成功以后直接按照命令启动即可:

npm run start // 不会热更新
npm run start:dev // 热更新

启动项目以后,请求**http://localhost:3000**地址可以获取**Hello World!**

做到这儿的时候就证明你简单程序已经搭建成功啦!你可真是太棒啦!

当然我们这样做的话,肯定是不好管理的,我们就得改改文件结构了,方便我们管理的同时也能让我们熟悉更多的知识点。

第一步:创建文件命令

根据以下命令可以创建核心的文件并且文件之间自动相互关联(引入导入等)

nest g controller auth/auth
nest g service auth/auth
nest g module auth/auth

第二步:重要文件说明

我们在书写接口的时候主要操作的文件就是这其中的三个,其他的基本上不用管他。

  • auth.controller.ts 调用接口名称
  • auth.service.ts 写接口逻辑
  • auth.module.ts 是导入模块处理

第三步:搭建项目文件

删除app文件

在这儿的时候我们可以将初始文件的app。。一类的文件进行删除,只保留app.module.ts,目的是其他文件所创建的文件进行导入即可。这样将会更好的管理你的项目文件。

  • app.service.ts
  • app.service.spes.ts
  • app.controller.ts
  • app.controller.spes.ts

只需要保留 app.module.ts

这个时候你的文件夹有以下:

- src
 --| auth
 --| app.module.ts
 --| main.ts

app.module.ts

auth文件中的接口你安装app.controller.ts和app.service.ts的方式去写一个简单的 Hello World! 就行,这应该不用多教把,如果你实在不会,那你就将全部看完,后面我贴了auth文件的所有代码。

示例:导入的auth文件,

import { Module } from '@nestjs/common';
import { AuthModule } from './auth/auth/auth.module';

@Module({
  imports: [AuthModule],
  controllers: [],
  providers: [],
})
export class AppModule {}

这个时候你在去启动项目,请求**http://localhost:3000**地址看可以获取Hello World! ?;如果能获取并且启动没有报错那就是没问题了

完成到这儿基本上基础模板就搭建好了,现在开始搭建数据库。

数据库

数据库首先肯定是安装塞,安装mysql2就可以啦!铛铛铛…

npm install mysql2
  • 创建entity/auth.entity.ts

因为typescript是严格格式嘛!所以我们需要声明我们表格中的字段名字以及类型,如果我们在各自的文件中去声明的话就显得臃肿和不方便管理,所以我们在src文件下创建一个entity文件,在此针对不同不同的文件声明不同的文件名称即可。

import { Column, Entity, PrimaryGeneratedColumn } from 'typeorm';

@Entity('ai')
export class AuthEntity {
  @PrimaryGeneratedColumn()
  id: number;

  /** 名字 */
  @Column({
    name: 'name',
  })
  name: string;
  /** path */
  @Column({
    name: 'path',
  })
  path: string;
}
  • auth.module.ts

然后导入entity文件,你注意看有注释的地方就行。

import { Module } from '@nestjs/common';
import { AuthService } from './auth.service';
import { AuthController } from './auth.controller';
import { AuthEntity } from "../../entity/auth.entity"; // 导入
import { TypeOrmModule } from "@nestjs/typeorm";

@Module({
  providers: [AuthService],
  controllers: [AuthController],
  imports: [TypeOrmModule.forFeature([AuthEntity])], // 主要修改的是这
})
export class AuthModule {}

  • auth.service.ts

注意看constructor将数据引入进来,我只知道大致意思,具体的还不是很清楚,大家可以去看看官网。下次弄懂了,在到这儿来解释(能想起来的话,哈哈哈)。

这串代码this.authRepository.find()就是就是在查询数据库的。我会在后面列一些常见的增删改查。

import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { AuthEntity } from "../../entity/auth.entity";

@Injectable()
export class AuthService {
  constructor(@InjectRepository(AuthEntity) private readonly authRepository: Repository<AuthEntity>) {} // 主要修改的是这

  getHello(): string {
    return 'Hello World----------------';
  }
  async getUser() {
    return await this.authRepository.find(); // 主要修改的是这
  }
}

CustomConfig 文件

mysql数据库基本信息配置

export default {
  // 启动端口
  port: 3000,
  // 数据库配置
  dbConfig: {
    type: 'mysql',
    host: 'localhost', 
    port: 3306,
    username: '', // 用户名
    password: '', // 密码
    database: '', // 数据库名称
    entities: ['./**/*.entity.js'],
    synchronize: false,
    logging: true,
  },
};

app.module.ts

最后就是在此文件中引入配置即可,然后启动项目,你就可以链接到服务器了。

import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { AuthModule } from './auth/auth/auth.module';
// 这个文件就是配置的数据库的文件夹
import CustomConfig from './config';

@Module({
  imports: [
    // 配置
    ConfigModule.forRoot({
      isGlobal: true,
      load: [CustomConfig],
    }),
    // 数据库
    TypeOrmModule.forRootAsync({
      imports: [ConfigModule],
      useFactory: (configService: ConfigService) =>
        configService.get('dbConfig'),
      inject: [ConfigService],
    }),
    AuthModule],
  controllers: [],
  providers: [],
})
export class AppModule {}

到此数据库搭建就算是完成了;是不是还行。

同学当你学习到此的时候,你基础的开发就完成了,你可能会说:注册登录呢?(单点登录),队列等功能的实现。我后续都会更新的,只要有时间这些都是会更新的,这个东西我原来做过一次,不难。期待吧!

增删改查的基本语法:

以下都是一些最基础的方式,如果需要了解更多的话,还是去看看官网有更多操作数据库的方式方法 TypeORM中文文档

名字的话我就以以上的代码为例: this.authRepository.find(),在此修改

<!--第一种-->
await this.authRepository.add()
<!--第二种-->
await this.authRepository.insert()
<!--查询单条数据-->
await this.authRepository.findOne({ where: { id: 1 } })
<!--查询全部数据-->
await this.authRepository.find()
await this.authRepository.delete({ id: 1 })
await this.authRepository.update({ id: 1 })

到此就完成了。后续有时间再跟大家陆续更新,感谢您的观看!!!

原文链接:https://juejin.cn/post/7356434494511972388 作者:雾恋

(0)
上一篇 2024年4月12日 上午10:11
下一篇 2024年4月12日 上午10:21

相关推荐

发表回复

登录后才能评论