Middleware Pipeline
MediumP3Coding
Implement createPipeline(), an Express/Koa-style middleware pipeline. It returns an object with:
use(middleware)appends a middleware and returns the pipeline (so calls chain).run(ctx)runs the middleware in order and returns a promise that resolves withctxwhen the whole chain has finished.
A middleware is (ctx, next) => any and may be async. Calling next() runs the following middleware and returns a promise that resolves when it (and everything after it) has finished, so code after await next() runs on the way back. Rules:
- If a middleware does not call
next(), later middleware do not run. - After the last middleware,
next()simply resolves. - If a middleware throws or rejects,
runrejects with that error. - Calling
next()more than once from the same middleware rejects with anErrorwhose message contains"next() called multiple times". - The pipeline can be run many times; each run is independent.
Example 1
- Input
- app.use(async (ctx, next) => { log('a1'); await next(); log('a2'); }); app.use(async (ctx, next) => { log('b'); await next(); }); await app.run({});
- Output
- a1, b, a2
Constraints
- 0 <= middleware count <= 10^3
Hints
Give it a real attempt first. Run shows which examples fail.
Saved automatically
Run checks the 3 visible tests, Submit all 11. ⌘Enter runs, ⌘⇧Enter submits.