UNPKG

870 BJavaScriptView Raw
1
2
3const cls = require('continuation-local-storage');
4
5const logger = require('./logger');
6
7let ns = null;
8
9// load config
10module.exports.init = function(config) {
11 const options = config && config.cls || {};
12 ns = options.namespace || 'igo';
13 cls.createNamespace(ns);
14};
15
16//
17module.exports.middleware = function(req, res, next) {
18 const namespace = cls.getNamespace(ns);
19 namespace.bindEmitter(req);
20 namespace.bindEmitter(res);
21 namespace.run(function() {
22 try {
23 next();
24 } catch (err) {
25 logger.error('Igo cls error: ' + err);
26 }
27 });
28};
29
30//
31module.exports.getNamespace = function(name) {
32 return cls.getNamespace(name || ns);
33};
34
35//
36module.exports.bind = function(callback) {
37 const namespace = module.exports.getNamespace();
38 if (namespace && callback) {
39 return namespace.bind(callback);
40 }
41 return callback;
42}