@@ -2,7 +2,7 @@ var loopback = require('../loopback');
22var juggler = require ( 'loopback-datasource-juggler' ) ;
33var remoting = require ( 'strong-remoting' ) ;
44var cls = require ( 'continuation-local-storage' ) ;
5-
5+ var domain = require ( 'domain' ) ;
66module . exports = context ;
77
88var name = 'loopback' ;
@@ -30,6 +30,13 @@ function context(options) {
3030 var scope = options . name || name ;
3131 var enableHttpContext = options . enableHttpContext || false ;
3232 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+
3340 // Return the middleware
3441 return function contextHandler ( req , res , next ) {
3542 if ( req . loopbackContext ) {
@@ -39,13 +46,19 @@ function context(options) {
3946 // Bind req/res event emitters to the given namespace
4047 ns . bindEmitter ( req ) ;
4148 ns . bindEmitter ( res ) ;
49+
50+ currentDomain . add ( req ) ;
51+ currentDomain . add ( res ) ;
52+
4253 // 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+ } ) ;
4962 } ) ;
5063 } ;
5164}
@@ -94,7 +107,7 @@ ChainedContext.prototype.reset = function(name, val) {
94107function chain ( child ) {
95108 if ( typeof child . getCurrentContext === 'function' ) {
96109 var childContext = new ChainedContext ( child . getCurrentContext ( ) ,
97- loopback . getCurrentContext ( ) ) ;
110+ loopback . getCurrentContext ( ) ) ;
98111 child . getCurrentContext = function ( ) {
99112 return childContext ;
100113 } ;
0 commit comments