全书目录

第七篇:NestJS 完全指南 —— 国际机场总调度宇宙

第八章:DTO + Validation —— 先过材料核验机,别让脏数据进跑道

1 分钟 230 字 第 188 / 962 个阅读单元

NestJS 很强调 DTO(Data Transfer Object)

它不是“为了优雅而多写几个类”,而是为了让请求边界清楚。

ts
// 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;
}

然后在全局启用校验:

ts
// 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:多余字段直接报错

类比成机场:

text
请求体
  ↓
DTO 表单模板
  ↓
ValidationPipe 核验机
  ├── 材料齐全 -> 放行
  ├── 材料格式错 -> 退件
  └── 偷塞额外字段 -> 拦下

这一步的工程价值极高,因为:

越早挡住脏数据,后面的业务逻辑就越干净。