Nest: Validation pipe primitive transformation not working

Created on 11 Aug 2020  路  4Comments  路  Source: nestjs/nest

Bug Report

Current behavior

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

Expected behavior

According to the migration guide from Nest 6 to 7, this should be auto transformed, therefore expected behaviour would be no validation errors.

Possible Solution

Environment


Nest version: 7.4.2

For Tooling issues:

  • Node version: 12.16.0
  • Platform: Mac
needs triage

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!

All 4 comments

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!

Was this page helpful?
0 / 5 - 0 ratings