MediumPro challengeJavaScriptTypeScript

Middleware Pipeline (compose)

Node.jsDesign

Implement compose(middlewares) that chains async middleware functions
(like Koa.js). Each middleware receives (req, next) where next() calls
the following middleware.

solve creates middlewares from a declarative ops array and runs them:

  • {op:'set', key, val} — adds key to req then calls next()
  • {op:'stop'} — marks req.stopped = true, does not call next()

Return the final req state after compose(middlewares)(req) resolves.

Sample tests

Test #1Two middlewares both run
Input: [[{"op":"set","key":"auth","val":true},{"op":"set","key":"log","val":1}],{}]
Output: {"log":1,"auth":true}
Test #2stop prevents further middlewares
Input: [[{"op":"set","key":"auth","val":true},{"op":"stop"},{"op":"set","key":"never","val":true}],{}]
Output: {"auth":true,"stopped":true}
Test #3Empty middleware list returns req unchanged
Input: [[],{}]
Output: {}
Test #4Preserves existing req properties
Input: [[{"op":"set","key":"x","val":1}],{"existing":true}]
Output: {"x":1,"existing":true}
Test #5Pass-through middleware defers to next
Input: [[{"op":"pass"},{"op":"set","key":"a","val":42}],{}]
Output: {"a":42}