第一次是寫中間件狈邑,是寫一個設(shè)置灰度的中間件蹂匹,當(dāng)時寫完挺有成就感的碘菜,今天特意去看了一下koa的源碼,了解了request,中間件和response到底是怎么組織的忍啸,其中我覺得關(guān)于多個中間件是如何組織的部分寫得特別好仰坦,所以記錄一下:
koa的請求和響應(yīng)是一個洋蔥模型,而中間件就是其中的重要組成计雌,像是一個函數(shù)套函數(shù)的結(jié)構(gòu)悄晃,每一次請求都經(jīng)過層層函數(shù)的處理,最后又一層層返回凿滤。
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)
}
}
}
}