forked from skonves/express-http-context
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathindex.js
40 lines (34 loc) · 1.02 KB
/
index.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
'use strict';
const cls = require('cls-hooked');
const nsid = 'a6a29a6f-6747-4b5f-b99f-07ee96e32f88';
/** Express.js middleware that is responsible for initializing the context for each request. */
function middleware(req, res, next) {
const ns = cls.getNamespace(nsid) || cls.createNamespace(nsid);
ns.run(() => next());
}
/**
* Gets a value from the context by key. Will return undefined if the context has not yet been initialized for this request or if a value is not found for the specified key.
* @param {string} key
*/
function get(key) {
const ns = cls.getNamespace(nsid);
if (ns && ns.active) {
return ns.get(key);
}
}
/**
* Adds a value to the context by key. If the key already exists, its value will be overwritten. No value will persist if the context has not yet been initialized.
* @param {string} key
* @param {*} value
*/
function set(key, value) {
const ns = cls.getNamespace(nsid);
if (ns && ns.active) {
return ns.set(key, value);
}
}
module.exports = {
middleware,
get: get,
set: set
}