管道
管道(Pipes) 主要用于对进入控制器方法的请求数据 进行验证(Validation) 和 转换
# 管道时机
客户端请求 → 中间件 → 守卫 → 拦截器 (前置) → **管道** → 控制器 → 服务 → 拦截器 (后置) → 异常过滤器
1.ValidationPipe(安装npm install class-validator class-transformer)
// export class CreateTest1Dto {} import { IsString, IsNumber } from 'class-validator'; export class CreateTest1Dto { @IsString() name: string; @IsNumber() age: number; @IsString() breed: string; }
create(@Body(new ValidationPipe()) createTest1Dto: CreateTest1Dto) { return this.test1Service.create(createTest1Dto); }
2.自定义管道
// 自定义管道 import { PipeTransform, Injectable, BadRequestException } from '@nestjs/common'; @Injectable() export class CustomPipe implements PipeTransform { transform(value: any) { if (typeof value !== 'number') { throw new BadRequestException('参数必须是数字'); } // return value.trim(); // 去除首尾空格 return value; } }
@Get('/pipe/:name') getName(@Param('name', new CustomPipe()) name: string) { return { name }; }
| 项目 | ValidationPipe | 自定义管道(Custom Pipe) |
|---|---|---|
| 是否内置 | ✅ 是(NestJS 官方) | ❌ 否,需要你手动编写 |
| 功能 | 自动验证 DTO + 自动类型转换(配合装饰器) | 任意处理逻辑:类型转换、去空格、数据库查询等 |
| 依赖 | class-validator + class-transformer |
无固定依赖(完全你自己写) |
| 使用场景 | 请求体 / 查询参数自动验证和转换 | 特殊场景参数处理,比如手机号掩码、ID验证等 |
| 配合 DTO 使用 | ✅ 必须 | ❌ 不一定 |
| 抛错行为 | 自动抛出 400 错误,带详细提示 | 你自己决定是否抛错,以及怎么抛错 |
浙公网安备 33010602011771号