how to use optional url parameters with NestjS

12,248

Solution 1

Router params name should be unique. The correct route path is:

Existing one is:

/route/:param1/config/:OptionalParam3?/:OptionalParam3?

Correction:

/route/:param1/config/:OptionalParam3?/:OptionalParam4?

Opinion: You can use query params if the params are optional. It is never a good idea to create optional param routes (disagreements agreed). Both serve the same purpose, but having them as the query params makes it more understandable for debugging and fellow developers.

Solution 2

If you are looking for how to annotate an optional query parameter, you can do it like so:

@ApiQuery({
  name: "myParam",
  type: String,
  description: "A parameter. Optional",
  required: false
})
async myEndpoint(
  @Query("myParam") myParam?: string
): Promise<blah> { 
  [...] 
}
Share:
12,248

Related videos on Youtube

Shchori
Author by

Shchori

Updated on July 10, 2022

Comments

  • Shchori
    Shchori almost 2 years

    I'm trying to replace our current backend service using Nestjs library, however, I want to create a route with 2 optional parameters in the URL something like :

    /route/:param1/config/:OptionalParam3?/:OptionalParam3?

    that means the route should catch :

    1. route/aa/config
    2. route/aa/config/bb
    3. route/aa/config/bb/cc

    how can I achieve that, I have tried to use ? and () but it's not working well.

  • Roman
    Roman about 3 years
    @Vinayak Sarawagi your approach makes sense. But for the sake of url readability for service users sometimes it worth to keep longer url, but with a short option
  • Cpp crusaders
    Cpp crusaders over 2 years
    not working for me.. not sure why getting the 404 Error.. my URL: resource1/:id1/resource2/:id2?
  • Cpp crusaders
    Cpp crusaders over 2 years
    figured another way as solution used something like this in NestJS @Delete([ 'resource1/:id1/resource2/:id2', 'resource1/:id1/resource2' ])