跳到主要内容

compose.js

一、认识


koa-composeKoa 实现中间件的核心逻辑。

二、源码


koa-compose

'use strict'

/**
* Expose compositor.
*/

module.exports = compose

/**
* Compose `middleware` returning
* a fully valid middleware comprised
* of all those which are passed.
*
* @param {Array} middleware
* @return {Function}
* @api public
*/

function compose (middleware) {
if (!Array.isArray(middleware)) throw new TypeError('Middleware stack must be an array!')
for (const fn of middleware) {
if (typeof fn !== 'function') throw new TypeError('Middleware must be composed of functions!')
}

/**
* @param {Object} context
* @return {Promise}
* @api public
*/

return function (context, next) {
// last called middleware #
let index = -1
return dispatch(0)
function dispatch (i) {
if (i <= index) return Promise.reject(new Error('next() called multiple times'))
index = i
let fn = middleware[i]
if (i === middleware.length) fn = next
if (!fn) return Promise.resolve()
try {
return Promise.resolve(fn(context, dispatch.bind(null, i + 1)))
} catch (err) {
return Promise.reject(err)
}
}
}
}

三、实现


function compose(middleware) {
if (!Array.isArray(middleware)) {
throw new TypeError("middleware 必须为函数数组");
}
for (const fn of middleware) {
if (typeof fn !== "function") {
throw 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[i];
if (i === 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)({});