Over a million developers have joined DZone.

Design Patterns in Express.js

Express is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications. Let's check out the different design patterns that we might see when working with Express.js.

· Web Dev Zone

Start coding today to experience the powerful engine that drives data application’s development, brought to you in partnership with Qlik.

Express is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications.

Below are some design patterns that we might see when working with Express.js...

Factory

This is a simple and common design pattern in JavaScript. Factory is a creational design pattern allowing us to abstract away object creation implementation details from the outside world. Express does this by only exporting the factory.

/**
 * Expose `createApplication()`.
 */

exports = module.exports = createApplication;

function createApplication() {
  var app = function(req, res, next) {
    app.handle(req, res, next);
  };
  ...
  return app;
}

And, using the factory to create an express application is as simple as this:

import express from 'express';
..
const app = express();

Middleware

Middleware is the term popularized by Express.js.

In fact, we can consider this design pattern a variant of Intercepting Filter and Chain of Responsibility

Image title

You may want to know more about this pattern—click here.

Decorator

The Decorator pattern extends (decorates) an object’s behavior dynamically. It's different from classical inheritance because new behavior is added at run time and only add to objects (not classes) that are decorated.

Image title


An easy example for this pattern is the req and the resp. In Node, the request and response objects have very limited APIs. Express enhances these objects by decorating them with a lot of new features.

Below is the function that takes request (req) and response (resp) objects and decorate them:

///lib/middleware/init.js
exports.init = function(app){
  return function expressInit(req, res, next){
    if (app.enabled('x-powered-by')) res.setHeader('X-Powered-By', 'Express');
    req.res = res;
    res.req = req;
    req.next = next;

    req.__proto__ = app.request;
    res.__proto__ = app.response;

    res.locals = res.locals || Object.create(null);

    next();
  };
};

Strategy

Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it.

Image title

It allows a strategy (algorithm) to be swapped out at runtime by any strategy without the client realizing it.

In Express, the Strategy pattern can be seen in the way Express supports various different template engines such as Pug, Mustache, EJS, swig, etc.. Take a look at here for the full list of supported engines

import express from 'express';
import exphbs from 'express-handlebars';
...
const app = express();
app.engine('.html', exphbs({...}));
app.engine('jade', require('jade').__express);

//Select the strategy '.html'
app.set('view engine', '.html');

Another example is the way Express supports "Content Negotiation"

Proxy

This is a design pattern that provide an object called proxy (or surrogate) that controls access to another object called subject. The proxy and the subject have the same interface. The proxy sits between the client and the subject intercepting all or some requests and forwarding them to the subject.

Image title


In Express, there're two types of middleware:

  • Application-level middleware

  • Router-level middleware

Apart from the fact that application level middleware bound to an application object and that router level middleware bound to a router instance, they are same. So, how does Express archive this ? By composition! The express application object holds an internal reference to a Router instance object.

this._router = new Router({
      caseSensitive: this.enabled('case sensitive routing'),
      strict: this.enabled('strict routing')
});

this._router.use(query(this.get('query parser fn')));
this._router.use(middleware.init(this));

With each supported API, the application object will do some logic checking and validation before forwarding requests to the internal router instance.


Note: There're more patterns that I don't list here such as: Singleton, Lazy Initialization, Event Emitter, etc.

Create data driven applications in Qlik’s free and easy to use coding environment, brought to you in partnership with Qlik.

Topics:
design pattens ,express.js ,node js ,javascript ,framework

Published at DZone with permission of Can Ho, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}