javascripturlnestjs

Correct param decorator usage


I am wondering if I am implementing correctly a controller action to parse a parameter from URL in Nest.js

In my AppController class I declared a function getUser

@Get('user/:id')
  async getUser(@Param('id') id:string): Promise<users>{
    return await this.prismaService.getUser(parseInt(id));
  }

The part that bugs me is the parseInt(id), is there a way to declare it as

@Get('user/:id')
  async getUser(@Param('id') id:number): Promise<users>{
    return await this.prismaService.getUser(id);
  }
 

And avoid parsing the int from the string, enforcing typing at a different level instead of handling parseInt errors?

Right now my problem is that if I declare it as shown and call the route with http://localhost:3000/user/1, the id parameter is still a string (a bit confusing for me since in the function signature it is a number and I was expecting it to throw an error at compile time or parse me a number already).

Debugging the second implementation


Solution

  • Typescript is only a tool to help the developer during development and build time. It, unfortunately, doesn't do much to enforce parameters at runtime. For that, you could use the ParseIntPipe from Nest, @Param('id', new ParseIntPipe()) id: number and if you pass something that isn't a number it will error, or you could go the full validation route and create a DTO.