edit
Informed in the comments bellow that passing an array will acieve the exact same thing, so no need for an additional module. :-)
I was looking for a way to do this too as my application is very granular, but I didn't want to nest everything as in the other answer.
I'm sure there is something more comprehensive out there already, but I did this in the end:
/**
* Macro method to group together middleware.
*/
function macro (...middlewares) {
// list of middlewares is passed in and a new one is returned
return (req, res, next) => {
// express objects are locked in this scope and then
// _innerMacro calls itself with access to them
let index = 0;
(function _innerMacro() {
// methods are called in order and passes itself in as next
if(index < middlewares.length){
middlewares[index++](req, res, _innerMacro)
} else {
// finally, next is called
next();
}
})();
}
}
And then use it like this:
var macro = macro(
middleware1,
middleware2,
middleware3
);
app.post('/rout', macro);