2014-11-12 11:36:16 +00:00
|
|
|
var loopback = require('../../lib/loopback');
|
2014-06-17 17:35:19 +00:00
|
|
|
|
|
|
|
module.exports = context;
|
|
|
|
|
|
|
|
var name = 'loopback';
|
|
|
|
|
2014-11-06 22:07:34 +00:00
|
|
|
/**
|
|
|
|
* Context middleware.
|
|
|
|
* ```js
|
|
|
|
* var app = loopback();
|
|
|
|
* app.use(loopback.context(options);
|
|
|
|
* app.use(loopback.rest());
|
|
|
|
* app.listen();
|
|
|
|
* ```
|
|
|
|
* @options {Object} [options] Options for context
|
|
|
|
* @property {String} name Context scope name.
|
|
|
|
* @property {Boolean} enableHttpContext Whether HTTP context is enabled. Default is false.
|
|
|
|
* @header loopback.context([options])
|
|
|
|
*/
|
|
|
|
|
2014-10-22 21:29:56 +00:00
|
|
|
function context(options) {
|
|
|
|
options = options || {};
|
|
|
|
var scope = options.name || name;
|
|
|
|
var enableHttpContext = options.enableHttpContext || false;
|
2015-03-27 13:45:37 +00:00
|
|
|
var ns = loopback.createContext(scope);
|
2014-12-01 10:36:34 +00:00
|
|
|
|
2014-06-17 17:35:19 +00:00
|
|
|
// Return the middleware
|
2014-10-22 21:29:56 +00:00
|
|
|
return function contextHandler(req, res, next) {
|
|
|
|
if (req.loopbackContext) {
|
|
|
|
return next();
|
|
|
|
}
|
2014-12-01 10:36:34 +00:00
|
|
|
|
2015-03-27 13:45:37 +00:00
|
|
|
loopback.runInContext(function processRequestInContext(ns, domain) {
|
|
|
|
req.loopbackContext = ns;
|
|
|
|
|
|
|
|
// Bind req/res event emitters to the given namespace
|
|
|
|
ns.bindEmitter(req);
|
|
|
|
ns.bindEmitter(res);
|
2015-02-10 01:28:20 +00:00
|
|
|
|
2015-03-27 13:45:37 +00:00
|
|
|
// Add req/res event emitters to the current domain
|
|
|
|
domain.add(req);
|
|
|
|
domain.add(res);
|
2014-12-01 10:36:34 +00:00
|
|
|
|
2015-03-27 13:45:37 +00:00
|
|
|
// Run the code in the context of the namespace
|
|
|
|
if (enableHttpContext) {
|
|
|
|
// Set up the transport context
|
|
|
|
ns.set('http', {req: req, res: res});
|
|
|
|
}
|
|
|
|
next();
|
2014-06-17 17:35:19 +00:00
|
|
|
});
|
|
|
|
};
|
|
|
|
}
|