Last active
July 2, 2019 03:02
-
-
Save bugventure/d804de7b951c337239b7 to your computer and use it in GitHub Desktop.
Express middleware chain implementation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
})(); | |
}; | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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