2015-12-01 50 views
2

我試圖使用continuation-local-storage包從不容易訪問的點訪問當前的快速請求/響應。node - continuation-local-storage

我創建了以下中間件:

var createNamespace = require('continuation-local-storage').createNamespace, 
    getNamespace = require('continuation-local-storage').getNamespace; 

const domain = 'ns.cls'; 

exports.configure = function(app) { 
    createNamespace(domain); 

    app.use(function(req, res, next) { 
    exports.set(req, res, "callcontext", { req, res }); 
    next(); 
    }); 
}; 

exports.set = function(req, res, name, value) { 
    var namespace = getNamespace(domain); 

    namespace.bindEmitter(req); 
    namespace.bindEmitter(res); 

    namespace.run(() => namespace.set(name, value)); 
}; 

exports.get = function(name) { 
    var namespace = getNamespace(domain); 
    return namespace.get(name); 
}; 

exports.getCallContext = function() { 
    return exports.get("callcontext"); 
}; 

然而,當我試圖訪問它是未定義的背景:

var localStorage = require('../middleware/local-storage'); 

module.exports = function(doc, ctx) { 
    var callContext = localStorage.getCallContext(); 
    console.log("value: " + callContext); 
}; 

有沒有人有什麼想法?

由於提前,

馬克

回答

2

createNameSpace應該被調用一次。此外,你必須在網上的錯誤

exports.set(req, res, "callcontext", { req, res }); 

應該像

exports.set(req, res, "callcontext", { key: value }); 

這是我使用它的方式:
設置

var session = require('continuation-local-storage').createNamespace('session') 
app.use(function(req, res, next) { 
    session.bindEmitter(req); 
    session.bindEmitter(res); 

    session.run(function() { 
     session.set('req', req); 
     next(); 
    }); 
    }); 

得到

var session = require('continuation-local-storage').getNamespace('session') 
session.get('req') 
+0

我是相信這是行不通的,除非你不用自己的承諾......這是很難避免的。我認爲每個承諾都會破壞運行環境。 – kboom