In this section, we will explore the implementation of routers within an Express application, with a focus on modularity. Modular routing is crucial for maintaining a clean, scalable, and maintainable codebase, especially in complex applications. We will also examine various types of routers, their use cases, key considerations, and best practices.
Router Initialization:
const UserRouter = require("express").Router();:
This line initializes a new router instance specifically for user-related routes, promoting separation of concerns.
Controller and Middleware Integration:
The router integrates various middleware and controller functions, such as:
checklogin allowUser setPath uploader bodyValidator
Exporting the Router:
module.exports = UserRouter;: Exports the configured router for integration with the main application router, facilitating modular architecture.One of the key components of Express.js is its routing system, which allows you to define routes for handling different HTTP methods.
Main HTTP methods (GET, POST, PUT, PATCH, DELETE) and the use method
use method is a bit different from the above methods. It’s used to apply middleware functions to your application. Middleware functions are functions that have access to the request object (req), the response object (res), and the next middleware function in the application’s request-response cycle. You can also use the use method to define routes for specific pathsBelow is an example of setting up a router for the user module in an Express application:
javascriptCopy code
const UserRouter = require("express").Router();
const userCTRL = require("./user.controller");
const checklogin = require("../../middlewares/auth.middleware");
const allowUser = require("../../middlewares/rbac.middleware");
const { setPath, uploader } = require("../../middlewares/uploader.middleware");
const { bodyValidator } = require("../../middlewares/validator.middleware");
const { UserCreateDTO } = require("./user.request");
UserRouter.route("/")
.post(
checklogin,
allowUser,
setPath('/user'),
uploader.single('image'),
bodyValidator(UserCreateDTO),
userCTRL.userCreate
)
.get(userCTRL.getallUsers);
UserRouter.route("/:id")
.get(userCTRL.userbyID)
.patch(checklogin, userCTRL.updateUserById)
.delete(checklogin, userCTRL.deleteUserById);
module.exports = UserRouter;