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
函數對屬性進行讀取和寫入操作。