Skip to content
Onsite

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 with ctx when 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, run rejects with that error.
  • Calling next() more than once from the same middleware rejects with an Error whose 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

Run checks the 3 visible tests, Submit all 11.