Created
June 24, 2016 01:26
-
-
Save akhoury/6b79edc4572ebdc644af0e91effee702 to your computer and use it in GitHub Desktop.
use async-hook instead of continuation-local-storage
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var asyncHook = require('async-hook'); | |
var path = require('path'); | |
var utils = require('../../public/src/utils'); | |
function CLS() { | |
var mem = {}; | |
var self = this; | |
this.storage = null; | |
asyncHook.addHooks({ | |
init: function (id, handle, provider, parentUid, parentHandle) { | |
mem[id] = self.storage; | |
}, | |
pre: function (id, handle) { | |
self.storage = mem[id]; | |
}, | |
post: function (id, handle) { | |
self.storage = null; | |
}, | |
destroy: function (id) { | |
delete mem[id]; | |
} | |
}); | |
asyncHook.enable(); | |
} | |
CLS.prototype.domain = function (cb) { | |
var self = this; | |
process.nextTick(function () { | |
self.storage = {}; | |
cb(); | |
self.storage = null; | |
}); | |
}; | |
var cls = new CLS(); | |
(function(ncls) { | |
ncls.http = function (req, res, next) { | |
cls.domain(function() { | |
ncls.set('request', req); | |
next && next(); | |
}); | |
}; | |
ncls.socket = function (socket, payload, event, next) { | |
cls.domain(function() { | |
ncls.set('request', utils.reqFromSocket(socket, payload, event)); | |
next && next(); | |
}); | |
}; | |
ncls.get = function (key) { | |
return cls.storage && cls.storage[key]; | |
}; | |
ncls.set = function (key, value) { | |
if (cls.storage) { | |
cls.storage[key] = value; | |
} | |
}; | |
ncls.setItem = ncls.set; | |
ncls.setItem = ncls.set; | |
})(exports); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment