Express routes with Builder pattern

In the last post, we were creating a common interface for creating express routes, thereby improving reusability.

We now want to take it up a notch. How about having some fun with Builder Pattern, using plain old Javascript Functions.

Creating express routes with Builder Pattern

So, I created a file RouteBuilder.js and it looks like this.

// RouteBuilder.js
const express = require("express");

const RouteBuilder = function () {
  this.path = undefined; //string
  this.method = undefined; //string
  this.middlewares = undefined; //array of middlewares
  this.controller = undefined; //final request handler
  this.router = express.Router();

  this.setPath = function (path) {
    this.path = path;
    return this;
  };
  this.setMethod = function (method) {
    this.method = method;
    return this;
  };
  this.setMiddlewares = function (middlewares) {
    this.middlewares = middlewares;
    return this;
  };
  this.setController = function (controller) {
    this.controller = controller;
    return this;
  };
  this.build = function () {
    this.router
      .route(this.path)
      [this.method.toLowerCase()](...this.middlewares, this.controller);
    return this.router;
  };
};

module.exports = RouteBuilder;

and you can invoke this RouteBuilder like this

const RouteBuilder  = require('./RouteBuilder');
const authMiddleware = require("../authMiddleware")
const validateMiddleware = require("../validateMiddleware")
const actionMiddleware = require("actionMiddleware")
const serviceMiddleware= require("serviceMiddleware")

const routeBuilder = new RouteBuilder();

const userController = (req, res, next) => {
  res.send({});
};

//build the route
let route = routeBuilder
  .setPath('/')
  .setMethod('GET')
  .setMiddlewares([
    authMiddleware,
    validateMiddleware,
    actionMiddleware,
    serviceMiddleware,
  ])
  .setController(userController)
  .build();

//Finally set the route to the app
app.use("/users", route); // here app is the express app.

Did you find this article valuable?

Support Tirtha Guha by becoming a sponsor. Any amount is appreciated!