NestJS matching route with different wildcards

Viewed 1370

Hello I want to match a route in NestJS like this:

@Controller('posts')
export class PostsController {
  @Get(:id)
  getPostById() {}

  @Get(:slug)
  getPostBySlug() {}
}

The problem is the request nevers hit the slug route, how can I configure the routes to make the id only match with numbers and the second only match with letters and dashes?

Thank you very much :)

3 Answers

This isn't possible, because when Express or Fastify sets up the router for this, it's just looking at something that matches a regex, and there's no qualifier that says "this is specifically a slug" or "this is definitely an id" so all Express or Fastify can do is match the first route. You would need to set up either a switch in your controller or service to call either method depending on the param, or you would need to make the routes identifiable before the use of the URL parameter. @Get('/id/:id') or @Get('/slug/:slug')

It looks like there is a path-to-regex package in @nest/common dependencies and I checked - you can really use it.

https://www.npmjs.com/package/path-to-regexp

Now you're able to make id match only numbers by setting regex:

@Get('/:id(\\d+)')

I didn't found the feature description in NestJS official docs, but it works. My @nest/common package versions is 8.4.1.

Related