Search code examples
node.jstypescriptexpresstypeorm

Nodej.s routing with express.js and TypeScript


I have question about node.js routes. Which routing version is correct? First version it's a standard version in express.js:

router.get('/packages/:name', (req, res) => {
//my example code
);

Second version with TypeScript. This version is from typeorm init command.

export const Routes = [{
    method: "post",
    route: "/user",
    controller: CustomerController,
    action: "createUser"
}];

Which version is better and why? About the second version, how i can add custom middleware? What is difference between first and second version?


Solution

    • Both the approaches are same. When you have a lot of routes for a single point like root/apiv1/[here all the routes] then the second one is preferable, if you have many dynamic routes, so its better to go with the first approach.
    • Talking about the language, you can achieve both kind of routing in plane JS and also in JS. But due to typecasting and validations, preferred language is typescript and way of routing depends on the situation.
    • Talking about the middleware, for the first approach we will pass the middleware just before the controller function, and for the second approach, we are bascially creating structures for our routes and we need to pass these routes to some route() end point, there we will define the middleware just like we are doing in the first approach.