Middleware chain
Implement compose(middlewares), the way Koa runs middleware. Each middleware is a function (ctx, next). compose returns a function (ctx) that runs the first middleware and returns a promise. Inside a middleware, next() runs the rest of the chain and returns a promise that settles when the rest is done; after the last middleware, next() resolves at once. A middleware that does not call next stops the chain. An error thrown anywhere rejects the returned promise. Calling next() twice in one middleware rejects with new Error('next() called multiple times'). In the tests each middleware records 'name in' and 'name out'; stop sets ctx.body and returns, throw throws Error(name), wait sleeps ms first, and twice calls next twice.
Start from
function compose(middlewares) {
// Return (ctx) => a promise that runs the chain.
}Hints
Each hint gives away a little more. Open one only when you need it.
Hint 1
Write dispatch(i): it runs middlewares[i] with ctx and () => dispatch(i + 1), and returns a promise.
Hint 2
Wrap the call in try and Promise.resolve, so a synchronous throw also becomes a rejection.
Hint 3
Keep the highest index dispatched so far; dispatching an index that is not higher means next() was called twice.
Solution
The app has this lab in JavaScript, TypeScript and Python. This page shows the JavaScript code.
From here on the page gives the method away. If you are still solving, go back to the hints.
JavaScript
function compose(middlewares) {
return function (ctx) {
let last = -1;
function dispatch(i) {
if (i <= last) return Promise.reject(new Error("next() called multiple times"));
last = i;
const fn = middlewares[i];
if (!fn) return Promise.resolve();
try {
return Promise.resolve(fn(ctx, () => dispatch(i + 1)));
} catch (error) {
return Promise.reject(error);
}
}
return dispatch(0);
};
}What an interviewer looks for
Express, Koa and most server frameworks are built on a middleware chain. Writing compose shows you understand how auth, logging and error handlers wrap a request on its way in and out.