Build a middleware chain with reduce
Build a middleware chain in JavaScript with reduceRight, where each function receives a context and a next function. Works in any Node.js.
Frameworks like Express and Koa pass a request through functions that each decide whether to call the next. reduceRight can build the chain from the last handler to the first.
const chain = (middlewares) => (ctx) =>
middlewares.reduceRight((next, middleware) => () => middleware(ctx, next), () => {})();
const app = chain([
(ctx, next) => {
ctx.log.push('a in');
next();
ctx.log.push('a out');
},
(ctx, next) => {
ctx.log.push('b in');
next();
ctx.log.push('b out');
},
(ctx) => {
ctx.log.push('handler');
},
]);
const ctx = { log: [] };
app(ctx);
console.log(ctx.log.join(' > '));a in > b in > handler > b out > a outGoing from the end, each step wraps the function that follows it in a next that calls the next middleware with the same context. The first step receives an empty function as its next. A middleware can run code before and after calling next(), which gives the nesting in the output.
This version is synchronous. For async middleware, make each step return a promise and await next(). A middleware that forgets to call next stops the chain, which is how guards work. See reduceRight.