介绍
koa-compose是koa用到的类库,用于koa中间件合并执行,compose是将多个函数合并成一个函数(eg: a() + b() +c()=> c(b(c()))),主要使用Promise/Async、递归调用实现。整个代码包括注释不到50行,非常精巧。
安装
npm install koa-compose
用法
compose([fun a{}, fun b{}, fun c{}, …])
例子
const compose=require('koa-compose')
async function test(){
const midFuns = []
midFuns.push(async (context, next) => {
console.log(1)
await next()
console.log(6)
})
midFuns.push(async (context, next) => {
console.log(2)
await next()
console.log(5)
})
midFuns.push(async (context, next) => {
console.log(3)
await next()
console.log(4)
})
console.log(midFuns)
await compose(midFuns)({})
}
test()
next 表示调用下一个midFun,打印结果如下:
1
2
3
4
5
6
源码
'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)
}
}
}
}
它返回的是一个已经合并好的函数,根据传入的函数递归调用dispatch。
- 首先调用dispatch(0),if (i <= index) 也就是 0<=-1不成立,继续往下走,这里主要避免在一个中间件内多次调用next
- 继续下一步 index = i,此时index=0了
- let fn = middleware[i] 获取到第一个中间件fn
- if (i === middleware.length) fn = next 这里的next为undefined
- 接下来就是最最核心的代码了,这里调用fn(也就是我们的中间件函数),并传入了两个参数一个是原来的context,一个是dispatch函数(递归调用,参数i值加1)
return Promise.resolve(fn(context, dispatch.bind(null, i + 1)));
dispatch.bind(null, i + 1) 返回一个新的dispatch函数,下面一个小例子,展示bind的作用
function multiply (x, y, z) { return x * y * z; } var double = multiply.bind(null, 2); //Outputs: 24 console.log(double(3, 4));
我们将前面的例子代码大致转换一下,看看最后是啥样
Promise.resolve(function(context){ //第一个中间件
console.log(1)
await Promise.resolve(function(context){ //第二个中间件 => await next()
console.log(2)
await Promise(function(context){ //第三个中间件 => await next()
console.log(3)
// await next() 最后一个next ,不会再调用其他中间件 直接Promise.resolve()
console.log(4)
}());
console.log(5)
}())
console.log(6)
}());