kartikk221 / hyper-express

High performance Node.js webserver with a simple-to-use API powered by uWebsockets.js under the hood.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Optional Parameter Route

arunnabraham opened this issue · comments

Hi I am using hyper-express for the first time. Looking for documentation to work. I am think most of its api syntax is like express. I have a question regarding routes.

Is there a way to get the optional paramenter in the router?. I checked examples and docs even tried express like syntax

like
router.get('/get-message/:session_id/:timestamp_before?', (request: Request, response: Response, next: MiddlewareNext) => { const getMessage = (new GetMessages(request)).get(); return response.json(getMessage); } );

but the "?" syntax does not work like in express. It just reads as a complete parameter.

Anyone tell me the way to do it if that exists or could you please implement the functionality?

Hey, there currently isn't support for that specific syntax since hyper-express for the most part, passes the path straight to uWS.js which has a fast router for working with path parameters. This can certainly be implemented in the future as a breaking change during a major version upgrade.

With that said, what you are trying to achieve can be done with wildcards like so:

router.get('/get-message/*', (request: Request, response: Response) => {
   // When splitting the path by slashes, the first item will be "get-message", second and third would be the optional params
   const [_, session_id, timestamp_before] = request.path.split('/');
});

Keep in mind, wildcard routes effectively listen for all subpaths on the wildcard, so you should bind the wildcard route last.
So the above example would handle all requests whose paths begin with "/get-message/....." so be mindful of that.

Thanks @kartikk221, I will consider that solution for now.