Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

@Transform() Boolean Cast Doesn't Work on DTO

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})

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading