当前位置: 首页 > 工具软件 > koa2-proxy > 使用案例 >

koa基础-源码分析(二)

谯皓君
2023-12-01

现在正式进入koa源码,找到koa文件下/lib/application.js文件

一、依赖项

const isGeneratorFunction = require('is-generator-function'); //判断是否为generator方法
const debug = require('debug')('koa:application'); // debug命名空间
const onFinished = require('on-finished');   // 请求完成时回调函数
const response = require('./response');    // response回调函数
const compose = require('koa-compose');  //中间件机制 、剥洋葱模型
const context = require('./context');  //上下文
const request = require('./request'); //request
const statuses = require('statuses'); //http状态包
const Emitter = require('events');  //node原生事件模块
const util = require('util');  //node原生工具模块
const Stream = require('stream');  //node原生stream模块
const http = require('http');  //node原生http模块
const only = require('only');  //用于返回对象指定属性
const convert = require('koa-convert');  // 基于koa生成器中间件转化成Promise中间件
const deprecate = require('depd')('koa');  //打印信息模块
const { HttpError } = require('http-errors'); // http错误模块

二、初始化

// 构造函数
  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);
    if (util.inspect.custom) {
      this[util.inspect.custom] = this.inspect;
    }
  }

三、listen方法

监听端口,开启服务

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

四、use方法

处理中间件

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

五、callback方法

返回http.createServer的回调函数,构造上下文

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方法

创建http.createServer的回调函数

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方法

创建上下文

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;
}
 类似资料: