Middleware pipeline là pattern cho phép xâu chuỗi nhiều hàm xử lý tuần tự, mỗi hàm nhận context và hàm next() để chuyển sang middleware tiếp theo — giống cách Express và Koa xử lý HTTP requests.
js
function compose(...fns) {
return (ctx, next) => {
let i = -1;
function dispatch(n) {
if (n <= i) return Promise.reject('next() called multiple times');
i = n;
const fn = fns[n] || next;
if (!fn) return Promise.resolve();
return Promise.resolve(fn(ctx, () => dispatch(n + 1)));
}
return dispatch(0);
};
}Hàm compose nhận danh sách middlewares và trả về một hàm duy nhất gọi lần lượt từng middleware.
- Biến
idùng để detect nếu next() bị gọi nhiều lần trong cùng một middleware, tránh loop vô hạn. - Câu hỏi nâng cao test hiểu biết về async composition, recursion, và Promise chaining.