koa——中間件機制中的http.createServer(app.callback())

中間件機制

使用koa創建一個基本的 http server

const Koa = require('koa');
const http = require('http');
const app = new Koa();
// Create HTTP server.
const server = http.createServer(app.callback());

有點不太理解http.createServer(app.callback())中的app.callback(),通過搜索查找發現是koa中封裝好的一個函數

app.callback就是作爲原生nodejs的callback來接收事件,我們都知道它將有兩個參數 req 和 res

具體封裝方式:

app.callback = function () {
    var fn = this.experimental
        ? compose_es7(this.middleware)
        : co.wrap(compose(this.middleware));
    var self = this;

    if (!this.listeners('error').length) this.on('error', this.onerror);

    return function (req, res) {
        res.statusCode = 404; //----- 入口
        var ctx = self.createContext(req, res); // ---- 封裝req,res在this上
        onFinished(res, ctx.onerror); // ---綁定結束方法
        fn.call(ctx).then(function () { // 以 ctx 爲 this 執行fn , 見下文
            respond.call(ctx);
        }).catch(ctx.onerror);
    }
};

其中,fn.call(ctx)是所有中間件執行的地方

var fn = this.experimental
        ? compose_es7(this.middleware)
        : co.wrap(compose(this.middleware));
//在非es7環境下,fn被co.wrap包裹,說明 compose(this.middleware) 將會返回一個generator.
//從裏到外分解 
//this.middleware 在application的構造函數裏面我們看到他就是一個數組。數組裏面的內容是什麼呢,在express裏面我們知道,app.use就是增加一箇中間件。我們看看koa的app.use

app.use

app.use = function (fn) {
    if (!this.experimental) {
        // es7 async functions are allowed
        assert(fn && 'GeneratorFunction' == fn.constructor.name, 'app.use() requires a generator function');
    }
    debug('use %s', fn._name || fn.name || '-');
    this.middleware.push(fn);
    return this;
};

參考鏈接:http://liyangready.github.io/2016/01/16/koa%E5%86%85%E9%83%A8%E8%A7%A3%E5%AF%86/

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章