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.


Detailed Explanation

  1. Router Initialization:

    const UserRouter = require("express").Router();:
    

    This line initializes a new router instance specifically for user-related routes, promoting separation of concerns.

  2. Controller and Middleware Integration:

    The router integrates various middleware and controller functions, such as:

    checklogin allowUser setPath uploader bodyValidator

  3. Exporting the Router:

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

Complete Code: User Router

Below 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;