user15913196
user15913196

Reputation:

class-transformer @Type() decorator doesn't work

I have a dto file:

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

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

The problem is, it seems @Type() decorator doesn't work. My UserModelDto looks like this:

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

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

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

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

When I send a request to a controller validation doesn't work for dataToUpdate field however for uuid it does. I've tried many ways but result remains the same.

Upvotes: 1

Views: 9589

Answers (4)

Mr WW
Mr WW

Reputation: 11

Please make sure that UserModelDto class constructor can be called without arguments. This is what class-transformer is doing when you specify @Type

Upvotes: 0

Jay McDoniel
Jay McDoniel

Reputation: 70111

To ensure errors on validation when extra properties are sent in, you need to make use of the forbidNonWhitelisted option in the ValidaitonPipe. If you just want to strip the values you can use transform: true and whitelist: true

Upvotes: 1

Papooch
Papooch

Reputation: 1645

You need to enable { transform: true } inside the ValidationPipe options:

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

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

Upvotes: 7

omidh
omidh

Reputation: 2822

You have forgot to add @validateNested decorator.

Upvotes: 1

Related Questions