Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use optional url parameters with NestjS

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.

like image 350
Shchori Avatar asked Jun 14 '20 11:06

Shchori


People also ask

How do you give an optional parameter in URL?

Adding Optional Parameters to your Order Page URLs To add a third parameter, add another ampersand & , then the name of the parameter, and then the value for the parameter.

How do I get parameters in Nestjs?

To get the URL parameter values or params from a GET request, we can use the @Param decorator function from the @nestjs/common module before the Controller method in Nestjs.

How do I redirect in Nestjs?

Redirection. To redirect a response to a specific URL, you can either use a @Redirect() decorator or a library-specific response object (and call res.redirect() directly). @Redirect() takes two arguments, url and statusCode , both are optional. The default value of statusCode is 302 ( Found ) if omitted.


2 Answers

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.

like image 55
Vinayak Sarawagi Avatar answered Oct 25 '22 04:10

Vinayak Sarawagi


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> { 
  [...] 
}
like image 36
AlejandroVD Avatar answered Oct 25 '22 04:10

AlejandroVD