聊一聊koa

目的

本文主要经由过程一个简朴的例子来诠释koa的内部道理。

koa的一个简朴例子

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

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

app.listen(3000);

koa内部文件构成

《聊一聊koa》

  • 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运转实例。

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要领。详细代码以下:

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

个中this.callback要领的源码以下:

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要领中另有另一行很主要的代码:

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包中,详细代码完成细节以下:

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要领的详细细节:

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函数离别处置惩罚一般要求相应流程和异常情况。

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

) {
// 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

;
if (this.body && statuses.empty

) this.body = null;
}

this.res指http.ServerResponse对象实例

末端

~~~~~

    原文作者:treeandgrass
    原文地址: https://segmentfault.com/a/1190000018367954
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞