Compose Middleware Like Koa
Write the code, see it run, pass the checks.
The problem
- medium
- Code
Write compose(middleware), where middleware is an array of functions, each called as fn(ctx, next). Return a function run(ctx) that calls the first one with ctx and a next function. Calling next() runs the next middleware with the same ctx and returns a promise that resolves once that one, and everything after it, has finished; after the last middleware, next() resolves straight away. A middleware that doesn't call next stops the chain there. Middleware may be async or plain functions. run(ctx) always returns a promise, even with no middleware or when one throws straight away: it resolves to undefined once the first middleware has finished, and rejects with any error a middleware throws or rejects with that no earlier middleware catches around its next(). Calling next() a second time in the same middleware rejects with an Error "next() called multiple times". run can be called any number of times, and each run is separate.
Your code must pass
- Runs middleware in onion order around next()
- Shares one ctx and waits for async middleware
- Lets a middleware stop the chain by not calling next
- Rejects when a middleware throws, unless an earlier one catches it
- Rejects a second call to next()
- Returns a promise even with no middleware