1.后端业务模块设计与拆分
模块设计:
创建用户模块
1 2
| nest g controller user nest g module user
|
1 2 3 4 5 6 7 8 9 10
| import { Controller, Get, Param, ParseIntPipe } from '@nestjs/common';
@Controller('user') export class UserController { @Get(':id') getUser(@Param('id', ParseIntPipe) id: number) { return 'get user:' + id; } }
|
创建鉴权模块
1 2 3 4 5 6 7
| @Controller('auth') export class AuthController { @Get() auth(){ return 'auth' } }
|
创建book模块
1 2 3 4 5 6 7 8
| @Controller('book') export class BookController { @Get(':id') getBok(@Param('id', ParseIntPipe) id){ return 'get book:'+id } }
|
2导入数据库与连接数据库
创建vben-book-dev数据库,并导入SQL。
然后集成TypeOrm
1
| npm install --save @nestjs/typeorm typeorm mysql2
|
在app.module中引入TypeormModule模块
1 2 3 4 5 6 7 8 9 10 11 12
| @Module({ imports: [TypeOrmModule.forRoot({ type:'mysql', host: 'localhost', port: 3306, username: 'root', password: 'root', database: 'vben-book-dev' }),UserModule, AuthModule, BookModule], controllers: [AppController, UserController, AuthController, BookController], providers: [AppService], })
|
3.数据库实体的使用
首先创建user的实体,在user目录下新建user.entity.ts.
注意:TypeOrmModule中的synchronize: true不能被用于生产环境,否则会导致生产环境数据丢失。因为它会根据项目中的entity文件在数据库中重新生成表
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| import { Column, Entity, PrimaryGeneratedColumn, Unique } from 'typeorm'; @Entity('admin_user') export class User { @Column() @PrimaryGeneratedColumn() id: number;
@Column() @Unique(['username']) username: string;
@Column() password: string;
@Column() role: string;
@Column() nickname: string;
@Column() active: number;
@Column() avatar: string; }
|
然后在usermodule中引入TypeormModule
1 2 3 4 5 6 7
| @Module({ imports:[TypeOrmModule.forFeature([User])], controllers: [UserController], providers: [UserService] }) export class UserModule {}
|
并在userService中编写代码
1 2 3 4 5 6 7 8 9 10 11
| export class UserService { constructor( @InjectRepository(User) private readonly usersRepository: Repository<User>, ) { }
findOne(id: number): Promise<User> { return this.usersRepository.findOneBy({ id }); } }
|
最后记得在Appmodule的typeormmodule工厂函数中设置autoLoadEntities: true
最后调用即可
3.2 增删改的代码
1.增
创建一个create-user.dto.ts用于校验,注意create-user.dto.ts中的字段与entity中的字段并不完全一致
1 2 3 4 5 6 7
| export class CreateUserDto{ username: string; password: string; role: string; nickname:string; avatar:string; }
|
随后写入create服务
1 2 3 4 5 6 7 8 9 10
| create(createUserDto: CreateUserDto): Promise<User> { const user = new User(); user.username = createUserDto.username; user.password = createUserDto.password user.role = createUserDto.role user.avatar = createUserDto.avatar user.active = 1 return this.usersRepository.save(user) }
|