聊一聊koa
目標
本文主要通過一個簡單的例子來解釋koa的內部原理。
koa的一個簡單例子
const Koa = require('koa'); const app = new Koa(); app.use(async ctx => { ctx.body = 'Hello World'; }); app.listen(3000);
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[code]) { // 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[code]; if (this.body && statuses.empty[code]) this.body = null; }
this.res指http.ServerResponse物件例項
結尾
~~~~~