NestJS 很强调 DTO(Data Transfer Object)。
它不是“为了优雅而多写几个类”,而是为了让请求边界清楚。
// src/flights/dto/create-flight.dto.ts
import { IsString, Length } from 'class-validator';
export class CreateFlightDto {
@IsString()
@Length(2, 10)
code: string;
@IsString()
@Length(2, 50)
destination: string;
}然后在全局启用校验:
// src/main.ts
import { ValidationPipe } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.useGlobalPipes(
new ValidationPipe({
whitelist: true,
transform: true,
forbidNonWhitelisted: true,
}),
);
await app.listen(3000);
}
bootstrap();这三个配置非常重要:
whitelist: true:没声明的字段自动剔除transform: true:把输入转成 DTO/class 类型forbidNonWhitelisted: true:多余字段直接报错
类比成机场:
请求体
↓
DTO 表单模板
↓
ValidationPipe 核验机
├── 材料齐全 -> 放行
├── 材料格式错 -> 退件
└── 偷塞额外字段 -> 拦下这一步的工程价值极高,因为:
越早挡住脏数据,后面的业务逻辑就越干净。