how to use optional url parameters with NestjS
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> {
[...]
}
Related videos on Youtube
Shchori
Updated on July 10, 2022Comments
-
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 :
route/aa/config
route/aa/config/bb
route/aa/config/bb/cc
how can I achieve that, I have tried to use
?
and()
but it's not working well. -
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 over 2 yearsnot working for me.. not sure why getting the 404 Error.. my URL: resource1/:id1/resource2/:id2?
-
Cpp crusaders over 2 yearsfigured another way as solution used something like this in NestJS @Delete([ 'resource1/:id1/resource2/:id2', 'resource1/:id1/resource2' ])