Skip to content

Instantly share code, notes, and snippets.

@bugventure
Last active July 2, 2019 03:02
Show Gist options
  • Save bugventure/d804de7b951c337239b7 to your computer and use it in GitHub Desktop.
Save bugventure/d804de7b951c337239b7 to your computer and use it in GitHub Desktop.
Express middleware chain implementation
module.exports = function chain() {
var steps = Array.apply(null, arguments);
return function middleware(req, res, next) {
(function dequeue() {
var step = steps.shift(),
callback = steps.length ? function (err) {
if (err) {
return next(err);
}
dequeue();
} : next;
if (!step) {
return next();
}
try {
step(req, res, callback);
}
catch (e) {
next(e);
}
})();
};
};
var express = require('express'),
chain = require('./chain.js'),
app = express();
function middleware1(req, res, next) {
next();
}
function middleware2(req, res, next) {
next();
}
express.use(chain(middleware1, middleware2));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment