@@ -2,7 +2,7 @@ var loopback = require('../loopback');
2
2
var juggler = require ( 'loopback-datasource-juggler' ) ;
3
3
var remoting = require ( 'strong-remoting' ) ;
4
4
var cls = require ( 'continuation-local-storage' ) ;
5
-
5
+ var domain = require ( 'domain' ) ;
6
6
module . exports = context ;
7
7
8
8
var name = 'loopback' ;
@@ -30,6 +30,13 @@ function context(options) {
30
30
var scope = options . name || name ;
31
31
var enableHttpContext = options . enableHttpContext || false ;
32
32
var ns = createContext ( scope ) ;
33
+
34
+ var currentDomain = process . domain = domain . create ( ) ;
35
+ currentDomain . oldBind = currentDomain . bind ;
36
+ currentDomain . bind = function ( callback , context ) {
37
+ return currentDomain . oldBind ( ns . bind ( callback , context ) , context ) ;
38
+ } ;
39
+
33
40
// Return the middleware
34
41
return function contextHandler ( req , res , next ) {
35
42
if ( req . loopbackContext ) {
@@ -39,13 +46,19 @@ function context(options) {
39
46
// Bind req/res event emitters to the given namespace
40
47
ns . bindEmitter ( req ) ;
41
48
ns . bindEmitter ( res ) ;
49
+
50
+ currentDomain . add ( req ) ;
51
+ currentDomain . add ( res ) ;
52
+
42
53
// Create namespace for the request context
43
- ns . run ( function processRequestInContext ( context ) {
44
- // Run the code in the context of the namespace
45
- if ( enableHttpContext ) {
46
- ns . set ( 'http' , { req : req , res : res } ) ; // Set up the transport context
47
- }
48
- next ( ) ;
54
+ currentDomain . run ( function ( ) {
55
+ ns . run ( function processRequestInContext ( context ) {
56
+ // Run the code in the context of the namespace
57
+ if ( enableHttpContext ) {
58
+ ns . set ( 'http' , { req : req , res : res } ) ; // Set up the transport context
59
+ }
60
+ next ( ) ;
61
+ } ) ;
49
62
} ) ;
50
63
} ;
51
64
}
@@ -94,7 +107,7 @@ ChainedContext.prototype.reset = function(name, val) {
94
107
function chain ( child ) {
95
108
if ( typeof child . getCurrentContext === 'function' ) {
96
109
var childContext = new ChainedContext ( child . getCurrentContext ( ) ,
97
- loopback . getCurrentContext ( ) ) ;
110
+ loopback . getCurrentContext ( ) ) ;
98
111
child . getCurrentContext = function ( ) {
99
112
return childContext ;
100
113
} ;
0 commit comments