koa源码笔记(一)

前言

  • 最近在看koa的源码。写框架是不可能的,这辈子都不会写框架,pr也不会提,就只有看看源码做做笔记,才能维持生活的样子
  • koa包下面只有四个js文件,十分简洁,其他功能分别放在其他对应的npm包中。


    image

application.js

  • 这个文件是koa的主入口,也是暴露了koa应用的class类。当然也是继承自Emitter。
  • 这篇主要介绍application.js里面的一些函数,同时理一下koa框架的工作流程。

constructor

  • 构造函数里初始化了三个属性context、request、response,原型分别来自其他三个js文件,用Object.create继承原型。这三个文件后面会再介绍。
constructor() {
    .......
    this.context = Object.create(context);
    this.request = Object.create(request);
    this.response = Object.create(response);
}

listen

  • listen方法,会调用原生的http模块,http.createServer方法新建一个http服务器,并监听传入的端口号。回调函数调用callback,这个函数里会依次执行中间件函数,后面会介绍。
    const server = http.createServer(this.callback());
    return server.listen(...args);

use

  • use方法,用于加载中间件函数,传入参数非函数类型时会抛错。然后如果是generator函数,则会调用koa-convert模块,把他转换为普通函数。
  • koa实例有一个数组属性middleware表示使用了的中间件,use方法把中间件函数push到middleware中。最后返回实例对象this,以便可以链式调用
  use(fn) {
    if (typeof fn !== 'function') throw new TypeError('middleware must be a function!');
    if (isGeneratorFunction(fn)) {
      fn = convert(fn);
    }
    this.middleware.push(fn);
    return this;
  }

callback

  • callback在掉用listen时,就会执行;最后返回一个handleRequest函数,在createServer执行完毕后执行。
  • 同时用koa-compose模块,把middleware中间件数组,进行处理变成一个相当于generator函数。
  • 然后用createContext函数生成一个context上下文对象。
    const fn = require('koa-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;

createContext

  • 这个方法自然就是生成一个context对象,上下文对象应该是koa框架的核心内容。下面介绍下context对象的一些属性
    • request:继承自request.js,调用Object.create新建的对象
    • response:继承自response.js,调用Object.create新建的对象
    • app:指向this,也就是application实例对象
    • req:http.createServer方法产生的原生req对象
    • res:http.createServer方法产生的原生res对象
    • originalUrl: 等于req.url
    • cookies:通过cookie模块生成的一个封装好的node cookie实例(具体api参考cookie模块)
  createContext(req, res) {
    const context = Object.create(this.context);
    const request = context.request = Object.create(this.request);
    const response = context.response = Object.create(this.response);
    context.app = request.app = response.app = this;
    context.req = request.req = response.req = req;
    context.res = request.res = response.res = res;
    request.ctx = response.ctx = context;
    request.response = response;
    response.request = request;
    context.originalUrl = request.originalUrl = req.url;
    context.cookies = new Cookies(req, res, {
      keys: this.keys,
      secure: request.secure
    });
    request.ip = request.ips[0] || req.socket.remoteAddress || '';
    context.accept = request.accept = accepts(req);
    context.state = {};
    return context;
  }

handleRequest

  • 这个方法执行的时候,context已经生成了,然后中间件们被处理成了一个fnMiddleware函数。
  • 然后调用fnMiddleware(ctx),把context作为参数传入,处理完成后再用respond(ctx)处理返回response。
  • 当然这些过程中,都会有对错误的监听以及处理,有个onerror函数来处理。
  • res的状态码默认为404,即在中间件里面没得到正确的数据就返回404。
handleRequest(ctx, fnMiddleware) {
    const res = ctx.res;
    res.statusCode = 404;
    const onerror = err => ctx.onerror(err);
    const handleResponse = () => respond(ctx);
    onFinished(res, onerror);
    return fnMiddleware(ctx).then(handleResponse).catch(onerror);
}

response

  • 这个函数就是通过已经处理好了的ctx对象,再做一些处理,最后调用ctx.res.end()方法返回最终的response报文。
function respond(ctx) {
  // allow bypassing koa
  if (false === ctx.respond) return;

  const res = ctx.res;
  if (!ctx.writable) return;

  let body = ctx.body;
  const code = ctx.status;

  // ignore body
  if (statuses.empty[code]) {
    // strip headers
    ctx.body = null;
    return res.end();
  }

  if ('HEAD' == ctx.method) {
    if (!res.headersSent && isJSON(body)) {
      ctx.length = Buffer.byteLength(JSON.stringify(body));
    }
    return res.end();
  }

  // status body
  if (null == body) {
    body = ctx.message || String(code);
    if (!res.headersSent) {
      ctx.type = 'text';
      ctx.length = Buffer.byteLength(body);
    }
    return res.end(body);
  }

  // responses
  if (Buffer.isBuffer(body)) return res.end(body);
  if ('string' == typeof body) return res.end(body);
  if (body instanceof Stream) return body.pipe(res);

  // body: json
  body = JSON.stringify(body);
  if (!res.headersSent) {
    ctx.length = Buffer.byteLength(body);
  }
  res.end(body);
}

小结

  • 总结一下koa框架的工作流程:
    • 首先constructor构造函数生成application实例(app) ==>>
    • 调用use方法加载中间件方法,推入middleware数组中 ==>>
    • 调用listen函数,新建http服务器,监听端口==>>
    • 初始化context上下文对象,使用koa-compose处理中间件函数,生成fnMiddleware函数 ==>>
    • fnMiddleware函数处理ctx上下文对象,也就是依次调用中间件函数处理ctx ==>>
    • 根据处理后的得到的ctx,返回http response。

你可能感兴趣的:(koa源码笔记(一))