聊一聊koa

目標

本文主要經過一個簡單的例子來解釋koa的內部原理。html

koa的一個簡單例子

const Koa = require('koa');
const app = new Koa();

app.use(async ctx => {
  ctx.body = 'Hello World';
});

app.listen(3000);

koa內部文件組成

clipboard.png

  • application.js中包含了Application類和一些輔助方法
  • context.js主要做用是承載上下信息,並封裝了處理上下文信息的操做
  • request.js中封裝了處理請求信息的基本操做
  • response.js中封裝了處理響應信息的基本操做

koa內部

在文章開頭的例子中,執行const app = new koa()時,實際上構造了一個Application實例,在application的構造方法中,建立了context.js、request.js、response.js代碼的運行實例。下文約定request值request.js代碼運行實例,response指response.js運行實例,context指context.js運行實例。node

constructor() {
    super();

    this.proxy = false;
    this.middleware = [];
    this.subdomainOffset = 2;
    this.env = process.env.NODE_ENV || 'development';
    this.context = Object.create(context);
    this.request = Object.create(request);
    this.response = Object.create(response);
    if (util.inspect.custom) {
      this[util.inspect.custom] = this.inspect;
    }
  }

調用app.listen(3000)方法監聽3000端口的http請求,listen方法內部建立了一個http.Server對象,並調用http.Server的listen方法。具體代碼以下:git

listen(...args) {
    debug('listen');
    const server = http.createServer(this.callback());
    return server.listen(...args);
  }

其中this.callback方法的源碼以下:github

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;
  }

該方法返回一個handleRequest函數,做爲createServer的參數,當http.Server實例接收到一個http請求時,會將請求信息和請求響應對象傳給handleRequest函數,具體指將http.IncomingMessage的實例req,和http.ServerResponse的實例res傳給handleRequest方法。其中this.createContext函數的源碼以下:數據庫

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.state = {};
    return context;
  }

上面代碼的主要做用是將請求信息和響應信息封裝在request.js和response.js的運行實例中,並建立上下文對象context,context包含了application實例、request實例、response實例的引用。在this.callback方法中還有另外一行很重要的代碼:json

const fn = compose(this.middleware);

能夠從Application的構造方法知道this.middleware是一個數組,該數組用來存儲app.use方法傳入的中間件方法。Application的use方法具體代碼實現細節以下,其中最關鍵的一行代碼是this.middleware.push(fn)。數組

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;
  }

compose方法的實現包含在koa-compose包中,具體代碼實現細節以下:app

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!')
  }

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

compose方法接收this.middleware數組,返回一個匿名函數,該函數接收兩個參數,上下文實例context和一個next函數,執行該匿名函數會執行this.middleware數組中的全部中間件函數,而後在執行傳入的next函數。在Application的callback方法的最後將執行上下文對象和compose方法返回的匿名函數做爲參數調用this.handleRequest方法。接下來看一下this.handleRequest方法的具體細節:dom

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

在this.handleRequest方法中建立了錯誤處理方法onError和返回響應的方法handleResponse
fnMiddleware就是compose方法返回的匿名函數。在this.handleRequest方法的最後執行匿名函數,並傳入hanldeResponse和onError函數分別處理正常請求響應流程和異常狀況。koa

return fnMiddleware(ctx).then(handleResponse).catch(onerror);

執行fnMiddleware函數,其實是執行以前傳入全部中間件函數。在中間函數中能夠拿到上下文對象的引用,經過上下文對象咱們能夠獲取到通過封裝的請求和響應實例,具體形式以下:

app.use(async ctx => {
  ctx; // 這是 Context
  ctx.request; // 這是 koa Request
  ctx.response; // 這是 koa Response
});

在中間件方法中能夠設置響應頭信息、響應內容。以及讀取數據庫,獲取html模版等。將須要返回給用戶端的數據賦值給上下文對象context的body屬性。respond方法的具體實現以下:

function respond(ctx) {
  // allow bypassing koa
  if (false === ctx.respond) return;

  if (!ctx.writable) return;

  const res = ctx.res;
  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) {
    if (ctx.req.httpVersionMajor >= 2) {
      body = String(code);
    } else {
      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);
}

respond方法的主要做用是對返回的內容進行一些處理,而後調用node.js的http.ServerResponse實例的end方法,將具體內容返回給用戶端。

request.js和response.js

在Application的createContext方法中,將node.js的請求(http.IncomingMessage)和響應對象(http.ServerResponse)分別賦值給了request.js和response.js文件代碼實例對象。
request.js中主要包含了處理請求的方法(實際上都是get方法,或者獲取器),獲取請求數據,例如:

get host() {
    const proxy = this.app.proxy;
    let host = proxy && this.get('X-Forwarded-Host');
    if (!host) {
      if (this.req.httpVersionMajor >= 2) host = this.get(':authority');
      if (!host) host = this.get('Host');
    }
    if (!host) return '';
    return host.split(/\s*,\s*/, 1)[0];
  },

上面的代碼中this.req是http.IncomingMessage實例,包含了http請求信息。
response.js中包含了處理請求響應的操做。例如設置響應狀態:

set status(code) {
    if (this.headerSent) return;
    assert(Number.isInteger(code), 'status code must be a number');
    assert(code >= 100 && code <= 999, `invalid status code: ${code}`);
    this._explicitStatus = true;
    this.res.statusCode = code;
    if (this.req.httpVersionMajor < 2) this.res.statusMessage = statuses[code];
    if (this.body && statuses.empty[code]) this.body = null;
  }

this.res指http.ServerResponse對象實例

結尾

~~~~~

相關文章
相關標籤/搜索