kartikk221 / hyper-express

High performance Node.js webserver with a simple-to-use API powered by uWebsockets.js under the hood.
MIT License
1.73k stars 89 forks source link

Optional Parameter Route #233

Closed arunnabraham closed 7 months ago

arunnabraham commented 7 months ago

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?

kartikk221 commented 7 months ago

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.

arunnabraham commented 7 months ago

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