类转换器 @Type() 装饰器不起作用

问题描述 投票:0回答:4

我有一个 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
则有效。我尝试了很多方法,但结果还是一样。

node.js typescript nestjs class-validator class-transformer
4个回答
7
投票

您需要在

{ transform: true }
选项中启用
ValidationPipe

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

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


1
投票

为了确保发送额外属性时验证错误,您需要使用

forbidNonWhitelisted
中的
ValidaitonPipe
选项。如果您只想删除值,可以使用
transform: true
whitelist: true


1
投票

您忘记添加

@validateNested
装饰器。


0
投票

请确保 UserModelDto 类构造函数可以在不带参数的情况下调用。这就是当您指定@Type

时类转换器所做的事情
© www.soinside.com 2019 - 2024. All rights reserved.