Set the validation pipe globally with transform true:
app.useGlobalPipes(new ValidationPipe({ transform: true }));
Have a route taking path params e.g.:
@Get(':val')
methodName(@Param() params: PathParamsWithPropertiesThatWeWantToBeIntegers) {
}
class PathParamsWithPropertiesThatWeWantToBeIntegers {
@IsInt()
val: number;
}
Try to call the route e.g /route/5
Validation errors:
val must be an integer number
According to the migration guide from Nest 6 to 7, this should be auto transformed, therefore expected behaviour would be no validation errors.
Nest version: 7.4.2
For Tooling issues:
- Node version: 12.16.0
- Platform: Mac
Route parameters always come in as strings. This is a problem with class-transformer
not Nest. Please report it there accordingly.
To fix this, enable the implicit type conversion https://github.com/typestack/class-transformer#implicit-type-conversion
app.useGlobalPipes(
new ValidationPipe({
transformOptions: { enableImplicitConversion: true },
}),
);
Thanks, I think I tried that and it works for that particular use case. What would happen though if the model was declared as a string with @IsString() validator, I presume that would then fail as will have turned the route param value into a number? I have stuck with specifying
@Type(() => Number)
in places where I want conversion
@kamilmysliwiec I'm curious why we would need to use the "implicit conversion" (i.e. using the type information that is provided by typescript), where my understanding is the app.useGlobalPipes(new ValidationPipe({ transform: true }));
should transform the types based on the decorators, i.e. @IsInt()
should attempt to transform a string to an integer. Any insight would be helpful, thanks!
Most helpful comment
@kamilmysliwiec I'm curious why we would need to use the "implicit conversion" (i.e. using the type information that is provided by typescript), where my understanding is the
app.useGlobalPipes(new ValidationPipe({ transform: true }));
should transform the types based on the decorators, i.e.@IsInt()
should attempt to transform a string to an integer. Any insight would be helpful, thanks!