22

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.

Shchori
  • 233
  • 1
  • 2
  • 5

4 Answers4

21

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.

Vinayak Sarawagi
  • 914
  • 7
  • 11
  • `@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 – Roman Apr 15 '21 at 18:10
  • not working for me.. not sure why getting the 404 Error.. my URL: resource1/:id1/resource2/:id2? – Cpp crusaders Jan 20 '22 at 04:41
  • 1
    figured another way as solution used something like this in NestJS @Delete([ 'resource1/:id1/resource2/:id2', 'resource1/:id1/resource2' ]) – Cpp crusaders Jan 20 '22 at 14:38
  • This approach is correct but doesn't consider the project is using NestJS, which offers a lot more readability – Alvin Jan 12 '23 at 03:06
19

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> { 
  [...] 
}
AlejandroVD
  • 1,576
  • 19
  • 22
6

I solved this problem by using @Query decorator as below:

Here is my controller:

@Get()
async getAll(@Query('someParameter') someParameter?: number) {
  return this.service.getAll(someParameter);
}

Here is my client (Angular) service:

getAll(someParameter?: number) {
  return this.http.get(`apiUrl/controllerAddress?someParameter=${someParameter}`
  );
}
Mohsen
  • 971
  • 2
  • 11
  • 29
-1

You can use this structure:

-route -aa -config -[[...id]].js

It will work for the routes : route/aa/config/{anything}