Getting 500 when using auto transform validation in nestjs

Viewed 428

I'm using NestJS and I'm trying to get auto-transform for params to work. I've added that code:

app.useGlobalPipes(
  new ValidationPipe({
    transform: true,
  }),
);

And I have a controller that receives a numeric param:

@Get(':id')
getStuff(@Param('id') id: number) {
  ...
}

The problem is when I try to use a non numeric param (path/to/controller/one instead of path/to/controller/1) I receive a 500 Internal Server error instead of the expected 400 response. What am I missing?

Thanks!

1 Answers

The ValidationPipe does not work on primitive types (string, boolean, number), so you'll need to use the ParseIntPipe or something similar on the @Param() decorator to ensure you get the same kind of logic being applied. What's probably happening is something in your service is expecting a number and it's getting a string, and doesn't know how to process it from there.

On option would be to create a DTO for the URL parameters like so

export class ControllerRouteParamDto {
  @Transform(({ value }) => Number.parseInt(value, 10))
  @IsNumber()
  id: number;
}

The @Transform() is necessary due to url and query parameters coming in as strings and not their related types.

Related