Middlewares
JS Functions
Medium
25 min
async
promises
design-patterns
closures
Implement compose(middlewares). It takes an array of middleware functions and returns a single function run(context, next?) that executes them as a pipeline.
Each middleware has the signature (context, next) => any. Calling next() runs the rest of the pipeline and returns a promise that settles when the downstream middlewares have finished. A middleware can therefore do work before next(), wait for it, and then do more work afterwards. This is the "onion" model used by Koa.
const log = [];
const run = compose([
async (ctx, next) => {
log.push('timer start');
await next();
log.push('timer end');
},
async (ctx, next) => {
ctx.user = 'ada';
await next();
},
async (ctx) => {
ctx.body = `hello ${ctx.user}`; // doesn't call next: the pipeline stops here
},
]);
const ctx = {};
await run(ctx);
// ctx.body -> 'hello ada'
// log -> ['timer start', 'timer end']
Requirements
- Middlewares run in array order, all sharing the same
contextobject. runalways returns a promise. It resolves (withundefined) once the first middleware has finished.- If a middleware does not call
next, the downstream middlewares don't run. - If
runis given anextfunction, it is called after the last middleware callsnext(). Otherwise, the lastnext()resolves immediately. - A middleware that throws, synchronously or asynchronously, rejects the promise returned by its caller's
next(). An upstream middleware can thereforetry/catcharoundawait next()to handle errors. An unhandled error rejectsrun's promise. - Calling
next()more than once in the same middleware rejects with anError. runcan be called many times; each call is independent.
Follow-up
- How does Express's
next(err)error handling differ from this? - How is Redux's
applyMiddlewarerelated? - How would you write a timeout middleware?
Spotted a mistake or a rights concern? Report an issue