数据校验与转换

1. 安装依赖包:

1
pnpm add class-validator class-transformer -S

2. 然后在main.ts中使用useGlobalPipes全局注册一下

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
27
28
29
30
31
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { Response } from './common/response'
import { HttpFilter } from './common/filter'
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger'
import { ValidationPipe } from '@nestjs/common';

async function bootstrap() {
const app = await NestFactory.create(AppModule)
// 设置全局前缀
app.setGlobalPrefix('api/v1')
// 生成文档
const options = new DocumentBuilder()
.setTitle('Nestjs API 接口文档') // 文档标题
.setDescription('Nestjs API 学习文档') // 文档描述
.setVersion('1.0') // 文档版本
.addBearerAuth() // 添加认证
.build() // 生成文档配置
// 创建 Swagger 文档
const document = SwaggerModule.createDocument(app, options)
// 挂载 Swagger 文档到 /api-docs 路由
SwaggerModule.setup('/api-docs', app, document)
// 响应拦截器
app.useGlobalInterceptors(new Response())
// 错误过滤器
app.useGlobalFilters(new HttpFilter())
// 参数校验
app.useGlobalPipes(new ValidationPipe())
await app.listen(process.env.APP_PORT);
}
bootstrap();

3.之后就可以在dto中加校验规则了

src/user/dto/login-user.dto.ts

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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
import { ApiProperty } from '@nestjs/swagger';
import { IsNotEmpty, Matches, MaxLength, MinLength } from 'class-validator';
export class LoginUserDto {
@IsNotEmpty({
message: '用户名不能为空'
})
@MinLength(4, {
message: '用户名长度不能小于4位'
})
@MaxLength(20, {
message: '用户名长度不能大于20位'
})
@Matches(/^[A-Za-z0-9_]+$/, {
message: '用户名只能包含字母、数字和下划线'
})
@ApiProperty({
example: 'admin',
description: '用户名'
})
username: string;
@IsNotEmpty({
message: '密码不能为空'
})
@MinLength(6, {
message: '密码长度不能小于6位'
})
@MaxLength(20, {
message: '密码长度不能大于20位'
})
@Matches(/^(?=.*\d)(?=.*[A-Z])|(?=.*\d)(?=.*[a-z])|(?=.*\d)(?=.*[^A-Za-z\d])|(?=.*[a-z])(?=.*[A-Z])|(?=.*[a-z])(?=.*[^A-Za-z\d])|(?=.*[A-Z])(?=.*[^A-Za-z\d])/, {
message: '密码必须至少包含数字、特殊符号、大小写字母中任意两个'
})
// 正则表达式确保特殊字符仅限于 !@#$%^&*
@Matches(/^[A-Za-z\d!@#$%^&*]+$/, {
message: '密码只能包含字母、数字和特殊字符(!@#$%^&*)'
})
@ApiProperty({
example: 'Pwd123456',
description: '密码'
})
password: string;
}

4.在controller中就可以使用@Body()注解接收参数了,并且会自动进行校验

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import { Controller, Get, Post, Body, Patch, Param, Delete, HttpStatus, HttpException, UseGuards, HttpCode } from '@nestjs/common';
import { UserService } from './user.service';
import { ApiOperation, ApiTags } from '@nestjs/swagger';
import { Public } from 'src/public/public.decorator';
import { LoginUserDto } from './dto/login-user.dto';

@Controller('user')
@ApiTags('用户') // 标记路由
export class UserController {
constructor(
private readonly userService: UserService
) { }

@Public()
@Post('login')
@HttpCode(HttpStatus.OK)
@ApiOperation({ summary: '用户登录' })
login(@Body() body: LoginUserDto) { // 使用LoginUserDto进行校验
return this.userService.login(body)
}
}

完结

以上步骤展示了如何在 NestJS 应用中实现数据校验与转换。通过安装必要的依赖、配置全局校验管道、在 DTO 中定义校验规则,并在 Controller 中使用这些规则,确保了应用的数据一致性和可靠性。