Created
June 22, 2011 20:35
-
-
Save danielbeardsley/1041099 to your computer and use it in GitHub Desktop.
Allows easy composition of a chain of connect.js-style middlewares
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
// Allows easy composition of a chain of connect.js-style middlewares in node.js | |
// given: | |
// function A(req,res,next){} | |
// function B(req,res,next){} | |
// composeMiddleware(A,B) will return a function(req,res,next) that passes the request | |
// through both handlers, just like Connect. If a next() is called with an error | |
// the call chain is stopped and the error is passed to the topmost next() | |
// If next() is called with the second parameter set to 'break' "next(null, 'break')" | |
// The chain is halted and route control is passed back to the original next() | |
function composeMiddleware(){ | |
var layers = Array.prototype.slice.call(arguments); | |
var handler = function(req,res,next){ | |
var i = 0; | |
// This is passed as the next() parameter | |
function nextLayer(err, escapeStack){ | |
if(err) return next(err); | |
// if the second param is 'break', break out of this stack by calling | |
// the original next() | |
if(escapeStack == 'break') return next(); | |
// if there are still layers left | |
if(i < layers.length){ | |
var layer = layers[i++]; | |
layer(req, res, nextLayer); | |
} else next(); // we're done with the stack. | |
} | |
nextLayer(); | |
} | |
return handler; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment