Reputation: 196
I am trying to convert a GET parameter to a boolean value.
I am using NestJS with class-validator and class-transformer.
I have set enableImplicitConversion
to true
in the validator pipe options.
class ExampleDto {
@Transform(value => value === 'true')
prop1: boolean;
}
Now the issue is, the GET parameter's value is always string, so the implicit transformation will always convert it to true
. I can prevent it by running a custom logic, but the implicit transformation is being performed before i can run any custom logic (i.e. the @Transform decorator).
Is there any way to get the value before it has been transformed?
or, Is there any other way I can achieve what I am trying to achieve? (eg. disable implicit conversion for a property, etc)
Upvotes: 2
Views: 2497
Reputation: 35
As @barley said the "obj" parameter it solves your problem.
So the "Transform" decorator will be like this:
class ExampleDto {
@Transform(({ obj }) => JSON.parse(obj.prop1))
prop1: boolean;
}
Upvotes: 0
Reputation: 1007
you need to implicitly check whether the Boolean string is true or false. if that doesn't match the condition return the original string value.
class ExampleDto {
@IsBoolean()
@Transform(({ value} ) => value === 'true' ? true : value === 'false' ? false : value)
prop1: boolean;
}
Upvotes: 0
Reputation: 196
I figured it out.
The function we pass to @Transform
decorator takes 3 parameters. One of them is the original object (without transformation).
Upvotes: 2