app.use(requestId);
app.use(authenticate); // may respond 401 and stop
app.use(rateLimit); // may respond 429 and stop
app.post("/orders", createOrder);
app.use(errorHandler); // (err, req, res, next)
Chain of Responsibility passes a request along a chain of handlers. Each handler either handles the request or passes it to the next handler. The sender doesn't know which handler will deal with it. You can change the chain without changing the handlers.
Express middleware is a common variant. Each middleware function receives req, res and next. It can do some work, then:
- call
next()to continue to the next middleware - end the chain by sending a response, as
authenticatedoes with a 401 - call
next(err)to skip to error-handling middleware. Express recognises error-handling middleware because it has four parameters.
The textbook version usually has one handler deal with the request. In Express, many middleware act on the same request.
Nest's request pipeline follows the same idea. It runs small handlers in order: middleware, guards, interceptors and pipes.
- Handlers form a chain, and each one handles the request or passes it on.
- The sender does not know which handler acts on the request.
- In middleware, next() continues, sending a response stops, and next(err) goes to error handlers.
- In middleware, many handlers usually act on one request.