-
Notifications
You must be signed in to change notification settings - Fork 4
/
context-factory.js
96 lines (76 loc) · 2.26 KB
/
context-factory.js
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
'use strict';
const continuationLocalStorage = require('cls-hooked');
const uuid = require('uuid');
const { set } = require("lodash");
class ContextFactory {
static getKoaMiddleware() {
const namespace = this.createNamespace();
return async function(ctx, next) {
await new Promise(namespace.bind(function(resolve, reject) {
namespace.set(
'request_id',
ctx.request.headers['x-request-id'] || uuid.v4()
);
namespace.bindEmitter(ctx.req);
namespace.bindEmitter(ctx.res);
next().then(resolve).catch(reject);
}));
};
}
static getExpressMiddleware() {
const namespace = this.createNamespace();
return (req, res, next) => {
namespace.bindEmitter(req);
namespace.bindEmitter(res);
namespace.run(() => {
namespace.set(
'request_id',
req.headers['x-request-id'] || uuid.v4()
);
next();
});
};
}
static run(callback) {
const namespace = this.createNamespace();
return namespace.runAndReturn(callback);
}
static setOnContext(key, value) {
const namespace = this.createNamespace();
namespace.set(key, value);
}
static getContextStorage() {
if (this._namespace && this._namespace.active) {
const { id, _ns_name, ...contextData } = this._namespace.active;
return this.convertDotNotationToObjects(contextData);
}
return {};
}
static convertDotNotationToObjects(data) {
const modifiedData = {};
Object.keys(data).forEach(key => set(modifiedData, key, data[key]));
return modifiedData;
}
static getRequestId() {
return this.getContextStorage().request_id;
}
static addContextStorageToInput() {
return (input) => Object.assign({}, input, this.getContextStorage());
}
static addRequestIdToInput() {
return (input) => Object.assign({}, input, { request_id: this.getRequestId() });
}
static destroyNamespace() {
if (this._namespace) {
continuationLocalStorage.destroyNamespace('session');
this._namespace = null;
}
}
static createNamespace() {
if (!this._namespace) {
this._namespace = continuationLocalStorage.createNamespace('session');
}
return this._namespace;
}
}
module.exports = ContextFactory;