Define route method dynamically #116
-
|
It has come to my attention that something I used to do with both express and fastify was build my own router and then register the routes dynamically. My router logic navigates through folders looking for TypeScript files that export a The following snippet is a close resemblance of how I expected it to work on HyperExpress. // src/routes/version.ts
import type { Response } from 'hyper-express';
export const url = '/version';
export const method = 'GET';
export const run = (res: Response) => {
res.json({
version: process.env.npm_package_version
});
};Now as for my router controller I iterate through files, do some transformations and eventually register said routes with: // src/structures/router.ts
// server is a HyperExpress.Server instance
server.any(
route.url,
{
middlewares
},
(req: Request, res: Response) => route.run(req, res)
);Now the problem with this is that I'm registering routes as // src/structures/router.ts
// server is a HyperExpress.Server instance
// route.method is a string that can be get/post/delete/put
server[route.method](
route.url,
{
middlewares
},
(req: Request, res: Response) => route.run(req, res)
);This is the output Are there any other ways to dynamically assign the method to a route since this attempt fails? PS: Is there a way to print all the routes registered to the WebServer? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 5 replies
-
|
You should likely implement some form a transformer for the creation part of your code that translates the exported constant method from your router files to a callable method on HyperExpress. Most route creation methods on the HyperExpress For example: let callable;
switch (route.method) {
case 'DELETE:
// Some route creation methods are different from the HTTP methods hence create cases like this for those
callable = 'del';
break;
default:
// Most route creation methods in HyperExpress are just lowercase forms of the HTTP methods
callable = route.method.toLowerCase();
break;
}
server[callable](
route.url,
{
middlewares
},
(req: Request, res: Response) => route.run(req, res)
); |
Beta Was this translation helpful? Give feedback.
You should likely implement some form a transformer for the creation part of your code that translates the exported constant method from your router files to a callable method on HyperExpress. Most route creation methods on the HyperExpress
ServerandRoutercomponents are just the lowercase versions of the original HTTP methods for those requests except for some special cases such asDELETEbeingdel(). So just be sure to go through the documentation and create special translation cases for these and you should be good to go.For example: