Home > Back-end >  @Transform() Boolean Cast Doesn't Work on DTO
@Transform() Boolean Cast Doesn't Work on DTO

Time:05-17

I'm using nestJS and class-transformer inside a DTO.

Here's a simple example of what I did and my issue:

    export class SomeDTO{
        @Transform(({ value }) => value === "true" || value === true || value === 1)
        @IsBoolean()
        doDelete : boolean;
    }

I tried even @Transform(({ value }) => { return value === "true" || value === true || value === 1})

Now, in my controller:

@Post("something")
someOperation(@Body()  data : SomeDTO){
    console.log(data); 
}

Logging the data, the intended boolean doDelete is still a string and wasn't transformed to its native boolean type.

Did tried proviiding any data like this: @Transform(({ value }) => { return false})

But in the controller, the data is still the same if we set the original DTO doDelete to true. It's not converting to false as we implied via @Transform().

Did I do something wrong? Appreciated the help and shedding some light.

I've tried these related references but nothing seems to work.

CodePudding user response:

If transform: true is not set as an option of the ValidationPipe then the @Transform() you are using will only be used in memory for the class-validator check and not persist as the value passed to your route handler. Setting transform: true means that Nest will pass back the plainToInstance value for what was already sent in.

  • Related