Compose onion-style async middlewares around a final handler
An edge server handles each request with a stack of small middlewares: one times the request, one checks a cache, one adds auth headers, and a final handler produces the response. Each middleware runs some code on the way in, hands control to the rest of the stack, and can then inspect or replace the result on the way out. Picture the layers of an onion.
Implement composeMiddleware(middlewares). It returns a function run(ctx, finalHandler) that runs the stack.
const run = composeMiddleware([mwA, mwB, mwC]);
run(ctx, finalHandler?) // => Promise of what mwA returns
// A middleware:
async function mw(ctx, next) {
// ...before
const result = await next(); // runs the rest of the stack
// ...after
return result; // passed back to the previous middleware
}
middlewares is not an array of functions, composeMiddleware throws a TypeError right away.middlewares array do not affect the composed function.run calls the first middleware with (ctx, next). Calling next() calls the next middleware with the same ctx object and its own next. After the last middleware, next() calls finalHandler(ctx) if one was given.next() always returns a promise. It resolves to whatever the next middleware returned (or the value its promise resolved to). After the last middleware, it resolves to finalHandler‘s result, or to undefined if there is no final handler. run(...) resolves to what the first middleware returned. With no middlewares, run resolves to the final handler’s result.next() stops the chain. Nothing after it runs.next() promise of the middleware before it rejects with that error. That middleware can catch it with try/catch; otherwise it keeps propagating, and run rejects.next() a second time, that call returns a promise rejected with an Error whose message contains "multiple times", and nothing downstream runs again.const log = [];
const run = composeMiddleware([
async (ctx, next) => {
log.push('timer in');
const response = await next();
log.push('timer out');
return { ...response, ms: 12 };
},
async (ctx, next) => {
if (ctx.path === '/health') return { status: 200, body: 'ok' }; // short-circuit
ctx.user = 'ana';
return next();
},
]);
await run({ path: '/profile' }, (ctx) => ({ status: 200, body: `hi ${ctx.user}` }));
// => { status: 200, body: 'hi ana', ms: 12 }
// log => ['timer in', 'timer out']
await run({ path: '/health' }, () => { throw new Error('not reached'); });
// => { status: 200, body: 'ok', ms: 12 }