跳到主要内容

实现

2023年08月03日
柏拉文
越努力,越幸运

一、认识


koa 中间件用于处理 http 的请求和响应。支持 Generator, 执行顺序是洋葱圈 模型。

二、实现


function compose(middleware) {
if (!Array.isArray(middleware)) {
return new TypeError("middleware 必须是一个函数数组");
}

for (const fn of middleware) {
if (typeof fn !== "function") {
return new TypeError("middleware 必须是一个函数");
}
}

return function (context, next) {
let index = -1;

function dispatch(i) {
if (i <= index) {
return Promise.reject(new Error("next() 函数不可以调用多次"));
}

index = i;
let fn = middleware[index];
if (index === middleware.length) {
fn = next;
}
if (!fn) {
return Promise.resolve();
}

try {
return Promise.resolve(fn(context, dispatch.bind(null, i + 1)));
} catch (error) {
return Promise.reject(error);
}
}

return dispatch(0);
};
}

三、调试


let fn1 = async function (context, next) {
console.log("fn1 之前");
await next();
console.log("fn1 之后");
};
let fn2 = async function (context, next) {
console.log("fn2 之前");
await next();
console.log("fn2 之后");
};
let fn3 = async function (context, next) {
console.log("fn3 之前");
await next(); // 最后一个中间件的 next 可有可无
console.log("fn3 之后");
};

let middleware = [fn1, fn2, fn3];
compose(middleware)({});