1、什么是Pipe
管道是用
@Injectable()装饰器批注的类,装饰器实现PipeTransform接口。在NestJS中,管道(Pipe)是一种用于转换输入数据的机制。它们允许你在数据到达处理程序之前对其进行转换、验证或者拒绝。管道可以用于处理HTTP请求的数据,也可以用于处理WebSocket消息、GraphQL查询等。
- 主要应用场景
- 验证:对输入数据进行验证,验证通过继续传递,否则抛出异常。
- 转化:将输入数据转化后输出。
2、使用ValidationPipe全局管道
-
安装两个依赖
npm install class-validator class-transformer -
然后在main中使用
import { NestFactory } from '@nestjs/core'; import { ValidationPipe } from '@nestjs/common' import { AppModule } from './app.module'; import { generateDocument } from './doc';
async function bootstrap() { const app = await NestFactory.create(AppModule); // Swagger文档创建 generateDocument(app) // 使用全局验证管道 app.useGlobalPipes(new ValidationPipe()) await app.listen(3000); } bootstrap();
-
在dto文件中,对字段格式进行校验
import { ApiProperty } from '@nestjs/swagger' import { Matches,IsNotEmpty,Length} from 'class-validator'
export class CreateUserDto {
@ApiProperty({example: '18625112911'}) @Matches(/^1\d{10}/g,{message: '请输入正确格式的手机号'}) phoneNumber: string; @IsNotEmpty() @ApiProperty({example: '666666'}) @Length(6,10) password: string; @ApiProperty({example: '123@qq.com'}) email: string;}
-
若没有输入正确格式的后端会响应提示,这里设置password长度为6-10,这里输入的不符合就报错了