how to use optional url parameters with NestjS

Viewed 22245

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.

3 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.

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> { 
  [...] 
}

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}`
  );
}
Related