Pipes 是一些转换或验证输入数据的类,在数据到达路由处理程序之前对其进行处理。它们作用于控制器方法的参数——要么转换它们(例如 string → number),要么验证它们(拒绝无效数据)。NestJS 中的验证建立在管道的基础上。
内置转换管道
ts
()
() {
..(id);
}
转换管道将输入转换为正确的类型(路由参数/查询参数始终是字符串),如果转换不可能则返回 400 错误。
// enable globally in main.ts
app.useGlobalPipes(new ValidationPipe({
whitelist: true, // remove properties not declared in the DTO
forbidNonWhitelisted: true, // throw if unknown properties are present
transform: true, // turn plain objects into DTO instances, convert types
}));
// with a DTO using class-validator decorators:
export class CreateUserDto {
@IsEmail() email: string;
@MinLength(8) password: string;
}
@Post()
create(@Body() dto: CreateUserDto) { // ValidationPipe validates the body automatically
// if invalid → 400 with details, BEFORE this runs
}
ValidationPipe 读取 DTO 的 class-validator 装饰器并自动验证传入数据——失败时返回详细的 400 错误,因此您的处理程序只会收到有效数据。
Request → ...middleware/guards/interceptors... → PIPES (transform/validate) → Handler
Pipes run JUST BEFORE the route handler, operating on its method arguments.
@Injectable()
export class TrimPipe implements PipeTransform {
transform(value: any) {
return typeof value === "string" ? value.trim() : value; // custom transformation
}
}
// usage: @Body(TrimPipe) ...
您实现 PipeTransform 的 transform() 方法来处理自定义验证/转换逻辑。
@UsePipes(new ValidationPipe()) // method or controller level
@Param("id", ParseIntPipe) // parameter level
app.useGlobalPipes(new ValidationPipe()) // global (most common for validation)
管道是 NestJS 安全处理输入的关键特性,也是框架验证系统的基础。
理解它们是必要的,因为几乎每个 API 端点都需要验证和转换输入:转换管道(ParseIntPipe 等)确保参数具有正确的类型,最重要的是——ValidationPipe 与 DTO 相结合提供了对照 class-validator 规则的自动声明式验证,在无效或恶意输入到达您的业务逻辑之前用清晰的错误拒绝它。
这对安全性(验证/清理不受信任的输入、删除意外属性)和健壮性(处理程序只接收有效数据)都至关重要。
了解如何使用合理的选项(whitelist、transform)启用全局验证管道、使用内置转换管道以及编写自定义管道,对于构建安全、结构良好的 NestJS API 是基础——管道和验证是框架中日常的、必须掌握的概念。