koa-koa-compose的洋葱模型

2021-02-01  本文已影响0人  ysdyyy

一:简介

koa-compose 将若干中间件合并成一个中间件,并且在中间件内部,原各个中间件的执行过程为洋葱式的。

二:源码

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) {
  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)
      }
    }
  }
}

源码中的重要逻辑:

三:next与洋葱模型

上回说到,next是用来执行下一个中间件的,那么在某中间件中,next的执行可能有以下情况

3.1 在最开始调用
let md1 = async function (ctx, next) {
    await next();
    console.log(1);
    console.log(2);
}

let md2 = async function (ctx, next) {
    await next();
    console.log(3);
    console.log(4);
}

let mds = compose([md1, md2]);
mds({}, null).then(() => {
    console.log('all finished');
}).catch(e => {
    console.error(e);
});

输出:

3
4
1
2
all finished
3.2 在中间调用
let md1 = async function (ctx, next) {
    console.log(1);
    await next();
    console.log(2);
}

let md2 = async function (ctx, next) {
    console.log(3);
    await next();
    console.log(4);
}

let mds = compose([md1, md2]);
mds({}, null).then(() => {
    console.log('all finished');
}).catch(e => {
    console.error(e);
});

输出:

1
3
4
2
all finished
3.3 在末尾调用
let md1 = async function (ctx, next) {
    console.log(1);
    console.log(2);
    await next();
}

let md2 = async function (ctx, next) {
    console.log(3);
    console.log(4);
    await next();
}

let mds = compose([md1, md2]);
mds({}, null).then(() => {
    console.log('all finished');
}).catch(e => {
    console.error(e);
});

输出:

1
2
3
4
all finished
3.4 总结

由于以下两条显而易见的规则:

故而中间件执行的过程有以下特征:

最后祭出那颗著名的葱:

2892151181-5ab48de7b5013_articlex.png

参考:
https://github.com/koajs/compose.git

上一篇下一篇

猜你喜欢

热点阅读