DEV Community

Tirtha Guha
Tirtha Guha

Posted on

3 3

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;
Enter fullscreen mode Exit fullscreen mode

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. 
Enter fullscreen mode Exit fullscreen mode

AWS GenAI LIVE image

How is generative AI increasing efficiency?

Join AWS GenAI LIVE! to find out how gen AI is reshaping productivity, streamlining processes, and driving innovation.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay