Run a middleware chain with next()
A middleware chain is the most useful closure pattern there is. Each function receives a shared context and a next callback; whatever it does before calling next() happens on the way in, and whatever it does after happens on the way out, once everything downstream has finished. Not calling next() short-circuits the rest of the chain — which is how an auth middleware rejects a request.
Implement createPipeline(). It returns an object with use(middleware), which registers a middleware and returns the pipeline itself so registrations can be chained, and run(context), which executes the middlewares synchronously in registration order and returns the same context object it was given. Each middleware is called as middleware(context, next). Calling next() runs the rest of the chain and returns once the rest of the chain has finished, so code after next() runs in reverse registration order. A middleware that never calls next() prevents every later middleware from running. Calling next() more than once in the same middleware throws new Error("next() called multiple times"). A pipeline with no middlewares simply returns the context.
What it has to do
useregisters a middleware and returns the pipeline so calls chain.runexecutes middlewares in registration order and returns the context it was given.- Code after
next()runs on the way back out, in reverse registration order. - A middleware that does not call
next()stops the rest of the chain. - Calling
next()twice throwsError("next() called multiple times").
Your workspace
Ready to check it?
5 tests run against your code, right here in your browser. Sign in to claim the XP when you pass.
AI Crack & Solution Assist
Stuck? Get instant AI hints or break down the optimal solution.
Stuck? The javascript course covers everything this challenge needs.