两只小蚂蚁

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

示例

先看看官网示例:

const Koa = require('koa');
const app = new Koa();
app.use(async (ctx, next) => {
  await next();
  const rt = ctx.response.get('X-Response-Time');
  console.log(`${ctx.method} ${ctx.url} - ${rt}`);
});
app.use(async (ctx, next) => {
  const start = Date.now();
  await next();
  const ms = Date.now() - start;
  ctx.set('X-Response-Time', `${ms}ms`);
});
app.use(async ctx => {
  ctx.body = 'Hello World';
});

app.listen(3000);

初始化

\\lib\applicationjs

module.exports = class Application extends Emitter {
  constructor(options) {
    super();
    options = options || {};
    this.proxy = options.proxy || false;
    this.subdomainOffset = options.subdomainOffset || 2;
    this.proxyIpHeader = options.proxyIpHeader || 'X-Forwarded-For';
    this.maxIpsCount = options.maxIpsCount || 0;
    this.env = options.env || process.env.NODE_ENV || 'development';
    if (options.keys) this.keys = options.keys;
    this.middleware = [];
    this.context = Object.create(context);
    this.request = Object.create(request);
    this.response = Object.create(response);
    // util.inspect.custom support for node 6+
    /* istanbul ignore else */
    if (util.inspect.custom) {
      this[util.inspect.custom] = this.inspect;
    }
  } 
}

主要是做些初始化,引入一个koa应用里会包含的三大对象

  1. Context
  2. Request
  3. Response

来看看Request和Response是什么:

\\lib\request.js
module.exports = {
  get header() {
    return this.req.headers;
  },
  ...
}
\\lib\response.js
module.exports = {
  get header() {
    const { res } = this;
    return typeof res.getHeaders === 'function'
      ? res.getHeaders()
      : res._headers || {}; // Node < 7.7
  },
  ...
}

看起来就是对原始请求和原始响应做了封装而已。再看看context:

const proto = module.exports = {
  ...
  get cookies() {
    if (!this[COOKIES]) {
      this[COOKIES] = new Cookies(this.req, this.res, {
        keys: this.app.keys,
        secure: this.request.secure
      });
    }
    return this[COOKIES];
  },

  set cookies(_cookies) {
    this[COOKIES] = _cookies;
  }
}

delegate(proto, 'response')
  .method('attachment')
  .method('redirect')
  .method('remove')
  .method('vary')
...

delegate(proto, 'request')
  .method('acceptsLanguages')
  .method('acceptsEncodings')
  .method('acceptsCharsets')
  .method('accepts')
  .method('get')
  .method('is')
...

看来cookie的处理被放在了context里面,并且代理了request和response的方法,相当于在context上也挂载了responserequest的方法、字段属性等。

由此来看主要的东西还是在res和req里面。

中间件

初始化完成后就是use添加中间件了:

//application.js
use(fn) {
  ...
  this.middleware.push(fn);
  return this;
}

use只是把传入的回调函数先存到middleware数组里而已

启动

接下来就是listen方法启动了:

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

callback() {
  const fn = compose(this.middleware);
  const handleRequest = (req, res) => {
    const ctx = this.createContext(req, res);
    return this.handleRequest(ctx, fn);
  };
  return handleRequest;
}
//compose来自于koa-compose
function compose (middleware) {
  //...
  return function (context, next) {
    // last called middleware #
    let index = -1
    return dispatch(0)
    function dispatch (i) {
      index = i
      let fn = middleware[i]
      if (i === middleware.length) fn = next
      if (!fn) return Promise.resolve()
      try {
        return Promise.resolve(fn(context, function next () {
          return dispatch(i + 1)
        }))
      } catch (err) {
        return Promise.reject(err)
      }
    }
  }
}

compose返回了一个函数,接受两个参数,context 和 next。context 是 KOA 中的 context,next 是所有中间件执行完后,框架使用者来最后处理请求和返回的回调函数。同时函数是一个闭包函数,存储了所有的中间件,通过递归的方式不断的运行中间件。

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

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

createContext用了Object.create又继承了一层this.context,然后对于Context对象挂载了一些属性。

所以handleRequest中middleware接受的context继承了构造函数创建的context。

整个流程就是handleRequest=>fnMiddleware=>handleResponse,也就是众所周知的洋葱模型了:

结论

KOA在nodejs的基础上进行了context和request&response的封装,采用洋葱模型将扩展性放到了中间件中。

posted on 2021-12-27 18:31  两只小蚂蚁  阅读(60)  评论(0编辑  收藏  举报