forked from maksrom/javascript-nodejs
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcls.js
More file actions
38 lines (29 loc) · 1.3 KB
/
cls.js
File metadata and controls
38 lines (29 loc) · 1.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
// This module initializes CLS
// and throws in additional modules to integrate it w/ other libs if needed
const clsNamespace = require("continuation-local-storage").createNamespace("app");
// Must teach bluebird work with CLS
// mz/fs uses bluebird by default if installed
// something else installs bluebird, so it gets used
// if I don't teach bluebird here, it won't keep CLS context, then yield fs.stat will spoil context
require('cls-bluebird')(clsNamespace);
exports.init = function(app) {
app.use(function*(next) {
var context = clsNamespace.createContext();
clsNamespace.enter(context);
// some modules like accessLogger await for this.res.on('finish'/'close'),
// so let's bind these emitters to keep CLS context in handlers
clsNamespace.bindEmitter(this.req);
clsNamespace.bindEmitter(this.res);
try {
clsNamespace.set('context', this);
yield* next;
} finally {
if (clsNamespace.get('context').requestId != this.requestId) {
console.error("CLS: wrong context", clsNamespace.get('context').requestId, "should be", this.requestId);
}
// important: all request-related events must be finished within request
// after request finished, the context is lost (kept by bindEmitter if any)
clsNamespace.exit(context);
}
});
};