Skip to content

Instantly share code, notes, and snippets.

@spollack
Last active December 27, 2015 10:39
Show Gist options
  • Save spollack/7312619 to your computer and use it in GitHub Desktop.
Save spollack/7312619 to your computer and use it in GitHub Desktop.
example of monkey-patching express to handle streamlinejs middleware. tested under express 2.x, but the same approach should work under express 3.x too.
var app = express.createServer();
var verbs = ['get', 'post', 'put', 'delete']; // whatever verbs you want to patch here...
patchExpressForStreamlineMiddleware(app, verbs, noop);
// now, you can make a call like this:
// app.get('/mypath', myStreamlineFunction)
// and have it work correctly. sequences of middleware will work too:
// app.get('/mypath2', myStreamlineFunction1, myStreamlineFunction2, myStreamlineFunction3)
// a no-op function (it will log errors, but that is it)
function noop(error) {
if (error) {
console.error('noop failure; error: ' + error);
}
}
// monkey-patch express to support streamlined route handler functions
function patchExpressForStreamlineMiddleware(app, verbs, noopFn) {
verbs.forEach(function (verb) {
var originalVerbHandler = app[verb];
app[verb] = function (/* mountpoint, fn1, fn2, ... */) {
// make a copy of the arguments pseudo-array, using array.slice
var argsWrapped = [].slice.apply(arguments);
// NOTE arguments one and onward are the handlers; we leave argument zero, the mountpoint, alone, and
// just pass it through
for (var i = 1; i < argsWrapped.length; i++) {
argsWrapped[i] = wrapFunction(arguments[i]);
}
// NOTE to support streamlined handler functions (where we have a _ callback added as a fourth parameter
// after the standard req, res, next params), invoke with a no-op callback parameter in the fourth slot;
// this makes streamline happy that some callback is being passed in, but will not cause any streamline
// pseudo-blocking nor cause any streamline futures to be created
function wrapFunction(fn) {
return function (req, res, next) {
fn(req, res, next, noopFn);
};
}
// NOTE must call with app as the this
originalVerbHandler.apply(app, argsWrapped);
};
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment