NestJS DTO 类设置类验证器和类转换器执行顺序

Use*_*ion 9 decorator typescript class-validator nestjs class-transformer

在 NestJS 中使用和包描述 DTO 类时,有没有办法设置装饰器的执行顺序class-validatorclass-transformer

当 的值foo设置为时,以下代码会失败null并出现错误:

需要一个字符串,但收到一个 null

@IsOptional()
@IsString()
@IsByteLength(1, 2048)
@Transform(({ value }) => validator.trim(value))
@Transform(({ value }) => validator.stripLow(value))
foo: string;
Run Code Online (Sandbox Code Playgroud)

即使我有一个isString装饰器应该检查是否确实传递了一个字符串,并且必须已经失败而不将执行传递给装饰@Transform器,但它并没有失败。

Jay*_*iel 12

类验证器基于类工作。进入服务器的请求有效负载只是简单的 JSON 对象。要更改此行为,如果您使用plainToClassNest的. 因此,装饰器优先于其他类验证器装饰器,并且首先执行操作。您可以通过使用多个管道或可能为装饰器提供默认值来解决此问题,但所发生的正是预期的效果。class-validatorValidationPipe@Transform()@Transform()


Sta*_*ity 6

通过2 ValidationPipe控制@Transfrom和Validator Decorator执行顺序

主要.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,
    }),

    new ValidationPipe({
      transform: true,
      transformOptions: { groups: ['transform'] },
    }),
  );

  await app.listen(4000);
}
bootstrap();
Run Code Online (Sandbox Code Playgroud)

创建用户.dto.ts

export class CreateUserDto {
  @ApiProperty({
    description: 'username',
    minLength: 4,
    maxLength: 64,
  })
  @Length(4, 64)
  name: string;

  @ApiProperty({
    description: 'password',
    minLength: 4,
    maxLength: 64,
  })
  @Length(6, 64)
  @Transform(({ value }: { value: string }) => hashSync(value), {
    groups: ['transform'],
  })
  password: string;
}
Run Code Online (Sandbox Code Playgroud)

这将首先运行@Length,然后运行@Transform。

使用 Deepl 进行翻译