如何在 GraphQL 变量中使用 class-validator 进行输入校验?

解读

国内一线/二线大厂在 GraphQL 落地时,普遍要求“零信任输入”——所有外部参数必须走 DTO 校验层。NestJS 官方把 class-validator 与 ValidationPipe 深度集成,但 GraphQL 的变量(variables)并不是走传统 HTTP body,而是随 query/mutation 一起进入 GraphQL 解析器。很多候选人在面试时只回答“用 ValidationPipe 就行”,却说不清 GraphQL 执行上下文里 Pipe 的生效顺序、装饰器优先级以及微服务体系下的差异,导致被追问“为什么同一个 DTO 在 REST 生效而 GraphQL 不生效”“如何对嵌套 InputType 做分组校验”“如何自定义 i18n 错误消息返回给前端”。本题的考点就是:在 NestJS + GraphQL 体系里,把 class-validator 真正“插”到 GraphQL 变量链路中,并保证校验失败时抛出的异常能被前端 Apollo/GraphiQL 正确识别,同时兼顾代码可维护与性能。

知识点

  1. GraphQL Code First 模式:@InputType()、@ArgsType()、@Field() 装饰器与 TypeGraphQL 的元数据注册流程。
  2. class-validator 核心装饰器:@IsString、@IsInt、@ValidateNested、@Type(() => X)、@IsOptional、@ValidateIf、分组校验 groups。
  3. ValidationPipe 的 transform、whitelist、forbidNonWhitelisted、exceptionFactory 配置项;GraphQL 执行器里 Pipe 的调用时机(先于 resolver 方法,晚于 GraphQL 参数解析)。
  4. GraphQL 异常规范:内置 UserInputError、ValidationError 与 NestJS 的 HttpException 如何映射到 Apollo Error Extensions。
  5. 微服务/Serverless 场景:当网关层转发 GraphQL 请求时,ValidationPipe 的 scope 与类实例生命周期(REQUEST scope)对冷启动性能的影响。
  6. 国际化:class-validator 的 i18n 消息模板与 NestJS 的 I18nService 结合,返回中文/英文错误提示。
  7. 性能优化:对列表型变量使用 @Transform 做按需校验,避免 O(n²) 嵌套;利用 class-validator 的 skipMissingProperties 与 cache 选项。

答案

步骤一:定义 DTO 并用 class-validator 装饰

// create-user.input.ts
import { InputType, Field, Int } from '@nestjs/graphql';
import { IsEmail, IsNotEmpty, MinLength, ValidateNested } from 'class-validator';
import { Type } from 'class-transformer';

@InputType()
export class AddressInput {
  @Field()
  @IsNotEmpty({ message: '省份不能为空' })
  province: string;

  @Field()
  city: string;
}

@InputType()
export class CreateUserInput {
  @Field()
  @IsEmail({}, { message: '邮箱格式不正确' })
  email: string;

  @Field()
  @MinLength(6, { message: '密码至少6位' })
  password: string;

  @Field(() => [AddressInput], { nullable: true })
  @ValidateNested({ each: true })
  @Type(() => AddressInput)
  addresses?: AddressInput[];
}

步骤二:在 resolver 中使用 @Args 接收变量

@Mutation(() => User)
async createUser(
  @Args('input') input: CreateUserInput, // 这里的 input 就是 GraphQL 变量
) {
  return this.userService.create(input);
}

步骤三:全局注册 ValidationPipe,确保对 GraphQL 生效

// main.ts
async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.useGlobalPipes(
    new ValidationPipe({
      transform: true,               // 启用 class-transformer
      whitelist: true,               // 去掉多余字段
      forbidNonWhitelisted: true,    // 多余字段直接报错
      exceptionFactory: (errors) => {
        // 把 class-validator 错误转成 GraphQL 友好格式
        const map = errors.reduce((acc, cur) => {
          acc[cur.property] = Object.values(cur.constraints)[0];
          return acc;
        }, {});
        return new UserInputError('参数校验失败', { validation: map });
      },
    }),
  );
  await app.listen(3000);
}

步骤四:在 GraphQL 中发送变量

mutation CreateUser($input: CreateUserInput!) {
  createUser(input: $input) {
    id
    email
  }
}

variables:

{
  "input": {
    "email": "foo",
    "password": "123",
    "addresses": [{ "province": "", "city": "上海" }]
  }
}

返回:

{
  "errors": [{
    "message": "参数校验失败",
    "extensions": {
      "code": "BAD_USER_INPUT",
      "validation": {
        "email": "邮箱格式不正确",
        "password": "密码至少6位",
        "addresses.0.province": "省份不能为空"
      }
    }
  }]
}

步骤五(可选):微服务多语言
在 ValidationPipe 的 exceptionFactory 里注入 I18nService,根据请求头 Accept-Language 动态返回中文或英文提示,满足国内 C 端/B 端双语需求。

拓展思考

  1. 分组校验:同一个 DTO 在“创建”和“更新”场景字段规则不同,可结合 class-validator 的 groups 与 NestJS 的 ValidationPipe 的 transformOptions.groups,通过自定义装饰器 @ArgsGroup('create') 动态传组名,实现“一 DTO 多场景”,避免冗余类。
  2. 列表大数据校验:当变量是上万条数组时,同步校验会阻塞事件循环,可改造 ValidationPipe 为“异步批校验”——先抽样 100 条快速失败,再后台任务全量校验,返回校验报告给前端。
  3. 与数据库唯一约束联动:class-validator 的 @IsUnique 需要查库,但 GraphQL resolver 里直接注入 Repository 会导致 Resolver 臃肿,可自定义 @IsUnique 装饰器,在 ValidationPipe 阶段使用 DATA_SOURCE 容器异步查库,失败时抛 UserInputError,实现“校验即业务”。
  4. 网关层缓存:在 Serverless 场景,冷启动时重复编译元数据会拖慢首包,可把 TypeGraphQL 的 schema 与 class-validator 的 metadata 在构建时持久化成 JSON,运行时直接加载,降低 40% 冷启动时间。