koa功能划分
koa
作为base node.js
的下一代web
应用框架,其具有简洁、健壮、富有表现力等特点。由Express
幕后的原班人马打造,充分利用async + await + promise
的特定,有效的规避了回调函数,且增强了错误处理。其核心主要包括两个部分,一个是koa
本身,一个是中间件的流程控制koa-compose
(koa源码解析)。
application.js
application.js
是koa
的入口文件,对外暴露了application
这个类,继承node
的events
。
const Emitter = require('events');
const http = require('http');
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);
if (util.inspect.custom) {
this[util.inspect.custom] = this.inspect;
}
}
use(fn) {
this.middleware.push(fn);
return this;
}
listen(...args) {
const server = http.createServer(this.callback());
return server.listen(...args);
}
};
application
就是应用,通过实例化该应用,在应用上挂载应用属性,并暴露了公用的api,其中使用最频繁的有两个,一个是listen
,一个是use
。listen
就是使用node
的http
模块调用http.createServer
进行服务创建,传入callback
函数,用于指定当接收到客户端请求时所需执行的处理,这callback
包含着应用的核心处理逻辑。主要包含了中间件的compose
处理,上下文的处理,对req
和res
的特殊处理。use
函数在应用中使用的最多,功能也比较简单,主要就是收集中间件,push
到middleware
数组中,然后交给koa-compose
进行中间价流程控制,use
函数return this
因此可以进行级联操作。
const Koa = require('koa');
// 实例化应用
const app = new Koa();
// 添加中间件
app.use(async (ctx, next) => {});
// 创建并启动server服务
app.listen(3000, () => {
console.log('server is running: http://loacalhost:30000')
});
context.js
const delegate = require('delegates');
const proto = module.exports = {};
delegate(proto, 'response')
delegate(proto, 'request')
context.js
就是koa
的应用上下文ctx
,其只是简单的对外暴露了一个对象,对象里面挂载了一些属性和方法,包括assert
断言,cookies
操作、throw
直接报错等。其重点在与使用delegate
对request
和reponse
的一些方法的代理,可以直接使用ctx
使用request
和reponse
对象的一些方法和属性,十分便捷。
request.js response.js
// request.js
module.exports = {}
// response.js
module.exports = {}
request.js
和response.js
都是简单对对外暴露一个对象,主要是定义了对callback
函数使用的原生req
和res
对象进行操作,如操作headers
、body
、scoket
等。其大量使用了访问器属性,使用get
和set
函数对属性进行读取和写入操作。