Nestjs框架学习

本文最后更新于:2023年7月28日 凌晨

安装与初始化

1
pnpm add @nestjs/cli -g
1
nest n nest-demo

路由controller

1
2
3
4
5
6
7
@Controller('user')
export class UserController {
@Get()
getUserInfo(@Query('id')) {
return id
}
}

模块modules

服务service

请求参数校验

👎在service/controller中校验入参

很容易想到的入参校验就是在函数中使用if/esle语句来判断

src/user/validators/user.dto.ts

1
2
3
4
export class CreateUserDto {
username: string
password: string
}

src/user/user.controller.ts

1
2
3
4
5
6
7
8
9
10
11
import ...

@Controller('user')
export class UserController {
@Post('/login')
login(@Body() { username, password }: CreateUserDto) {
if (!user || !password) return new HttpErrorByCode[400]('用户名/密码为空')

return this.UserService.login(username, password)
}
}

这虽然可以很快的解决问题, 但代码的可读性与维护性会大打折扣

使用管道(Pipe)修饰

nestjs内置了几个验证管道

  • ValidationPipe
  • ParseIntPipe
  • ParseFloatPipe
  • ParseBoolPipe
  • ParseArrayPipe
  • ParseUUIDPipe
  • ParseEnumPipe
  • DefaultValuePipe
  • ParseFilePipe
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import ...

@Controller('user')
export class TestPipeController {
@Get('/:id')
testPipe(
@Param(
'id',
new ParseIntPipe({
exceptionFactory: () => new HttpErrorByCode[400]('参数错误'),
}),
)
id: string,
) {
return id
}
}

class-validator方案

1
pnpm i class-validator class-transformer

src/user/validators/user.dto.ts

1


Nestjs框架学习
https://qingshaner.com/Nest框架学习/
作者
清山
发布于
2022年9月6日
许可协议