Revisiting the Middleware pattern in Javascript

The middleware pattern in Javascript is a close variation of the Chain of Responsibility (CoR) pattern in which a chain of functions are used to handle an incoming event, often in the form of a request.

Functions in the chain forward the event along the chain until one of the functions handles the event. This pattern offers some interesting benefits:

  • It decouples the sender of the event/request from the receiver by allowing one or several functions handle the event and process the data. Hence, intercepting the event data and acting as a filter.
  • No explicit knowledge between sender and receiver is required.
  • The chain of functions can be changed in run-time acting as an event pipeline.

In Javascript, the middleware pattern is extensively used by the Express, Connect and Koa frameworks.

The code below shows one possible implementation of the Middleware pattern:

var Middleware = function() {}; Middleware.prototype.use = function(fn) { var self = this; this.go = (function(stack) { return function(next) {, function() {, next.bind(self)); }); }.bind(this); })(this.go); }; Middleware.prototype.go = function(next) { next(); }; // example var middleware = new Middleware(); middleware.use(function(next) { var self = this; setTimeout(function() { self.hook1 = true; next(); }, 10); }); middleware.use(function(next) { var self = this; setTimeout(function() { self.hook2 = true; next(); }, 10); }); var start = new Date(); middleware.go(function() { console.log(this.hook1); // true console.log(this.hook2); // true console.log(new Date() - start); // around 20 });

The middleware pattern is a simple and time tested pattern but often overlooked in large JavaScript projects.

results matching ""

    No results matching ""