javascript / expert
Snippet
Functional Higher-Order Pipeline Composition for Request Contexts
Implements an onion-style functional middleware composition engine using closures and index assertions to process stateful request contexts sequentially.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
export function composeMiddleware(...middlewares) {return function (context) {let index = -1;function dispatch(i) {if (i <= index) throw new Error('next() called multiple times in middleware');index = i;const fn = middlewares[i];if (!fn) return context;return fn(context, function next() {return dispatch(i + 1);});}return dispatch(0);};}
nextjs
Breakdown
1
if (i <= index) throw new Error('next() called multiple times in middleware');
Guards against illegal duplicate invocations of the next continuation function within a single middleware step.
2
const fn = middlewares[i];
Retrieves the current middleware function targeted by the dispatch pointer index.
3
return fn(context, function next() { return dispatch(i + 1); });
Executes current middleware step supplying context and a closed-over next continuation callback.