洋葱模型

1. app.use()

 app.use(async (ctx, next) => {}); // 将中间件放入中间件数组

源码:

  use(fn) {
    if (typeof fn !== 'function') throw new TypeError('middleware must be a function!');
    if (isGeneratorFunction(fn)) {
      deprecate('Support for generators will be removed in v3. ' +
                'See the documentation for examples of how to convert old middleware ' +
                'https://github.com/koajs/koa/blob/master/docs/migration.md');
      fn = convert(fn);
    }
    debug('use %s', fn._name || fn.name || '-');
    this.middleware.push(fn); // 将中间件放入中间件数组
    return this;
  }

2. app.listen()

module.exports = app.listen(config.port, '0.0.0.0', () => {
  console.log('进入app');
});

源码:

  listen(...args) {
    debug('listen');
    // this.callback()为connection listener, 当客户端连接上服务器时会触发该函数,即handleRequest
    const server = http.createServer(this.callback()); 
    return server.listen(...args);
  }

  /**
   * Return a request handler callback
   * for node's native http server.
   *
   * @return {Function}
   * @api public
   */

  callback() {
    // 将中间件数组传入koa-compose, 得到一个返回函数,将该函数传入this.handleRequest
    const fn = compose(this.middleware);

    if (!this.listeners('error').length) this.on('error', this.onerror);

    const handleRequest = (req, res) => {
      const ctx = this.createContext(req, res);
      return this.handleRequest(ctx, fn);
    };

    return handleRequest;
  }

  /**
   * Handle request in callback.
   *
   * @api private
   */

  handleRequest(ctx, fnMiddleware) {
    const res = ctx.res;
    res.statusCode = 404;
    const onerror = err => ctx.onerror(err);
    const handleResponse = () => respond(ctx);
    onFinished(res, onerror);
    // fnMiddleware(ctx) 返回promise
    /* 
       return Promise.resolve(fn(context, function next () {
         return dispatch(i + 1)
       }))
       首先执行第一个中间件函数,传入context和next函数,next返回也是返回promise
   */
    return fnMiddleware(ctx).then(handleResponse).catch(onerror);
  }

3. 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) {
    // next 为undefined
    // 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, function next () {
          return dispatch(i + 1)
        }))
      } catch (err) {
        return Promise.reject(err)
      }
    }
  }
}

总结

整个流程为:
app.use函数将中间件放入中间件数组。当app接收到http请求时,会执行connection listener函数,这个函数中会去执行koa-compose返回的函数(return dispatch(0)),此时会执行第一个中间件函数,传入content和next函数,每个next函数也会返回一个promise。在中间件函数中await next(),即执行下一个中间件函数(return dispatch(i + 1)),直到所有的中间件都执行结束后,将undefined赋值给fn(if (i === middleware.length) fn = next)。

你可能感兴趣的:(洋葱模型)