Design templates in Express.js – DZone Web Dev


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 a few design patterns that we might see while working with Express.js …

Factory

This is a simple and common design pattern in JavaScript. Factory is a creative design model that allows us to abstract the implementation details of creating objects from the outside world. Express does this by exporting only 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 app is as easy as this:

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

Middleware

Middleware is the term popularized by Express.js.

In fact, we can think of this design pattern as a variation of Intercept filter and Chain of responsibility

You may want to know more about this model, click here.

Decorator

The Decorator pattern dynamically extends (decorates) the behavior of an object. This is different from classic inheritance because new behavior is added at run time and only added to objects (not classes) that are decorated.

Image Title

A simple example of this pattern is the req and the resp. In Node, request and response objects have very limited APIs. Express enhances these objects by decorating them with many new features.

Below is the function that takes the request (req) and response (resp) objects and decorates 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, wrap each one and make them interchangeable. The strategy allows the algorithm to vary regardless of the clients that use it.

Image Title

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

In Express, the Strategy model can be seen in the way Express supports different model engines like Pug, Mustache, EJS, swig, etc. 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 how Express supports “Content negotiation”

Proxy

This is a design template that provides an object called Proxy (or surrogate) which controls access to another called object matter. The Proxy and the subject have the same interface. The Proxy is between the client and the matter intercept all or part of the requests and forward them to the matter.

Image Title

In Express, there are two types of middleware:

Aside from the fact that the application-level middleware is bound to an application object and the router-level middleware is bound to a router instance, they are the same. So how does Express archive this? Through composition! The express application object contains 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 perform logical verification and validation before forwarding requests to the internal router instance.

To note: There are other models that I do not list here, such as: Singleton, Lazy Initialization, Event Emitter, etc.


Source link

Previous Design models are blueprints - Java DZone
Next Real World Design Patterns: Strategy

No Comment

Leave a reply

Your email address will not be published. Required fields are marked *