1 |
|
2 |
|
3 | const cls = require('continuation-local-storage');
|
4 |
|
5 | const logger = require('./logger');
|
6 |
|
7 | let ns = null;
|
8 |
|
9 |
|
10 | module.exports.init = function(config) {
|
11 | const options = config && config.cls || {};
|
12 | ns = options.namespace || 'igo';
|
13 | cls.createNamespace(ns);
|
14 | };
|
15 |
|
16 |
|
17 | module.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 |
|
31 | module.exports.getNamespace = function(name) {
|
32 | return cls.getNamespace(name || ns);
|
33 | };
|
34 |
|
35 |
|
36 | module.exports.bind = function(callback) {
|
37 | const namespace = module.exports.getNamespace();
|
38 | if (namespace && callback) {
|
39 | return namespace.bind(callback);
|
40 | }
|
41 | return callback;
|
42 | }
|