美文网首页
koa 的中间件设计

koa 的中间件设计

作者: 怪爵Geekknight | 来源:发表于2018-11-24 19:28 被阅读0次

koa的中间件是如何设计的?

koa是开源的,直接在github中获取源码:https://github.com/koajs/koa
package.json:

{
  main: 'lib/application.js'
}

application文件中定义了koa实例的方法,如:listen, use等等。
在listen方法中使用http.createServer(this.callback());定义http服务。
以下将listen, use, callback的源码展示。
application.js:

  listen(...args) {
    debug('listen');
    const server = http.createServer(this.callback());
    return server.listen(...args);
  }
  
  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;
  }
  
  callback() {
    const fn = compose(this.middleware);

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

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

    return handleRequest;
  }

use方法中的核心代码:

  this.middleware.push(fn);

callback方法中的核心代码:

  const fn = compose(this.middleware);

这里的compose方法是第三方模块koa-compose. koa-compose的源码只有48行,如下:

'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函数,通过递归把各个中间件连接起来。
因为return的类型是Promise,所以在使用next()的时候需要在前面加await。

相关文章

  • koa系列(三)

    文章内容:koa 中间件 以及 koa 中间件的执行流程。 一、什么是 Koa 的中间件 中间件就是匹配路由之前或...

  • koa 的中间件设计

    koa的中间件是如何设计的? koa是开源的,直接在github中获取源码:https://github.com/...

  • 知识点总结

    Koa2中间件 koa(面向node.js的表达式HTTP中间件框架)、koa-router(路由中间件)、koa...

  • Koa学习笔记

    中间件 Koa 的最大特色,也是最重要的一个设计,就是中间件(middleware) 中间件的概念 代码中的log...

  • 8KOA 静态文件

    静态文件 使用 koa-static 中间件实现静态文件访问 安装中间件 使用中间件 使用 koa-mount 自...

  • koa

    koa 学习 中间件 koa-router koa-router 获取get/post请求参数 koa-bodyp...

  • koa 中间件机制以及异常捕获

    koa 中间件机制以及异常捕获 koa 中间件机制解析 koa 的请求处理是典型的洋葱模型,下面是官方的配图,而这...

  • koa.js的使用(koa2)

    koa与Express简单比较Express connect 中间件 封装了 路由、视图,koa co中间件 不包...

  • koa 常用模块

    koa-router koa路由中间件https://github.com/alexmingoia/koa-rou...

  • Koa项目总结四:Koa静态资源的配置

    使用koa-static中间件来处理Koa项目中的静态资源。 1.1 koa-static安装: 1.2 koa-...

网友评论

      本文标题:koa 的中间件设计

      本文链接:https://www.haomeiwen.com/subject/yjbyqqtx.html