网站搜索

node.js - class-transformer @Type() 装饰器不起作用


我有一个 dto 文件:

export class UpdateUserDto {
  @IsUUID()
  public readonly uuid: string;

  @IsObject()
  @Type(() => UserModelDto)
  public readonly dataToUpdate: UserModelDto;
}

问题是,似乎 @Type() 装饰器不起作用。我的 UserModelDto 看起来是这样的:

export class UserModelDto {
  @IsUUID()
  @IsOptional()
  public uuid?: string;

  @IsEmail()
  @IsOptional()
  public email?: string;

  @IsString()
  @IsOptional()
  public password?: string;

  @IsJWT()
  @IsOptional()
  public refreshToken?: string;
}

当我向控制器发送请求时,dataToUpdate 字段的验证不起作用,但 uuid 字段的验证有效。我尝试了很多方法,但结果依然相同。

答案#1

您需要在 ValidationPipe 选项中启用 { transform: true }:

app.useGlobalPipes(
  new ValidationPipe({
    transform: true,
  }),
);

参考:https://docs.nestjs.com/techniques/validation#transform-payload-objects

答案#2

为了确保在发送额外属性时进行验证时出现错误,您需要在 ValidaitonPipe 中使用 forbidNonWhitelisted 选项。如果您只是想去除这些值,可以使用 transform: true 和 whitelist: true