koa2---源码解析---application.js(负责管理中间件,以及处理请求)

//constructor

constructor() {
    super();
    this.proxy = false;
    this.middleware = []; //中间件栈
    this.subdomainOffset = 2;
    this.env = process.env.NODE_ENV || 'development';
    this.context = Object.create(context); //Object.create(context)创建一个对象,这个对象的原型指向context
    this.request = Object.create(request);
    this.response = Object.create(response);
    //通过 Object.create()创造了三个对象
  }

//listen

listen(...args) {
  debug('listen');
  
   // 创建 http 实例服务,此时可看出 this.callback() 应返回一个带 req 与 res 作为参数的函数
  const server = http.createServer(this.callback())  
  return server.listen(...args);
}

//use,将引入的中间件进行保存,那么执行呢?执行之处关键在于callback中const fn = compose(this.middleware)
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)
  this.middleware.push(fn);
  //最后返回实例
  return this;
}

//callback

callback() {
  // 使用 koa-compose 将所有中间件集成返回为一个中间件函数,此时 fn 是一个闭包,
  // koa-compose 对中间件的顺序执行起到关键性作用,是 koa 整个中间件设计的核心。
  const fn = compose(this.middleware);

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

  // 返回 http.createServer() 参数中所需的回调函数
  const handleRequest = (req, res) => {
    const ctx = this.createContext(req, res);
    return this.handleRequest(ctx, fn);
  };

  return handleRequest;
}

从实例化 koa 对象 => 新建服务 => 存取并处理中间件 => 创建并关联上下文 => 顺序控制执行中间件 => 处理最后响应参数 => 全局监听整个中间件的执行过程及 debbug 整个 listen 的过程

对应函数的执行过程
Application.listen => Application.callback => koa-compose => Application.createContext => Application.handleRequest

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值