koa之koa-compose

介绍

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。

  1. 首先调用dispatch(0),if (i <= index) 也就是 0<=-1不成立,继续往下走,这里主要避免在一个中间件内多次调用next
  2. 继续下一步 index = i,此时index=0了
  3. let fn = middleware[i] 获取到第一个中间件fn
  4. if (i === middleware.length) fn = next 这里的next为undefined
  5. 接下来就是最最核心的代码了,这里调用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)
}());
  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
koa-composekoa 中的一个中间件组合函数,它的作用是将多个中间件函数合成为一个大的中间件函数,并且依次执行这些中间件。这个函数可以让我们在开发 koa 时更加灵活地使用中间件,可以方便地组合和重用中间件。 koa-compose 函数的使用方法非常简单,只需要将需要合并的中间件函数传入这个函数即可。这些中间件函数将会被合并成一个大的中间件函数,可以直接用于 koa 中的 use 方法。当请求过来时,koa-compose 函数会按照传入的中间件函数的顺序依次执行这些中间件。 以下是一个示例: ```javascript const Koa = require('koa'); const compose = require('koa-compose'); const app = new Koa(); const middleware1 = async (ctx, next) => { console.log('middleware1 start'); await next(); console.log('middleware1 end'); }; const middleware2 = async (ctx, next) => { console.log('middleware2 start'); await next(); console.log('middleware2 end'); }; const middleware3 = async (ctx, next) => { console.log('middleware3 start'); await next(); console.log('middleware3 end'); }; const composedMiddleware = compose([middleware1, middleware2, middleware3]); app.use(composedMiddleware); app.listen(3000, () => { console.log('server is running on port 3000'); }); ``` 以上代码将三个中间件函数合并成了一个大的中间件函数,然后通过 app.use 方法使用。当请求过来时,这三个中间件函数会依次执行,控制台输出如下: ``` middleware1 start middleware2 start middleware3 start middleware3 end middleware2 end middleware1 end ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值