DEV Community

Dibyojyoti Sanyal
Dibyojyoti Sanyal

Posted on • Edited on • Originally published at cloudnativemaster.com

Separate routing from business logic in node.js | Central response generation in node.js

Its important to keep the code that executes the business logic separate from the request routing. The separation helps code modularity and enhances separation of concerns. In my post What are routes in node.js ? How routes help writing modularized code ? I explained how we can use routers to handle multiple APIs, each API family can be separated using a separate router. You can easily imagine when the actual business logic is implemented the inline-function in the routers that handles the request will be much bigger and complicated.

First, as the number of APIs increase, keeping the routing logic and the business logic to process the requests in the same file is not going to scale and becomes cumbersome. We would like to separate the business logic from the routing logic. The router layer just should contain the routing logic and the business layer contains the business logic, the routing layer should use the business layer functions. For example, when we do user management (e.g create, update, view user) and order management (create, update, view order) we write all logic related to user management in a separate .js file and logic related to order management in another .js file. Here we write the business logic that is needed for user and order management. We can also write a separate function for each operation (e.g create user, view user, update user) in each of the files. Then we create a router for each routing family, for example a router for user management that starts with /user, a route for order management that starts with /order and so on. And finally we associate the particular REST call in the router with the particular operation in the business logic. For this we just have to import the .js file that has the business logic to the .js router file. You can see an example in my blog here

Second, in each function when we perform HTTP response generation we are repeating some of the logic necessary for response formulation. We should have a central method for request processing, used by all functions for all routers. I have also shown this in the same blog that I have linked above.

Top comments (0)