-
-
Notifications
You must be signed in to change notification settings - Fork 26
Expand file tree
/
Copy pathindex.js
More file actions
48 lines (41 loc) · 1.32 KB
/
Copy pathindex.js
File metadata and controls
48 lines (41 loc) · 1.32 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
39
40
41
42
43
44
45
46
47
48
'use strict';
const { AsyncLocalStorage } = require('async_hooks');
const STORAGE_KEY = Symbol.for(
'skonves/express-http-context/asyncLocalStorage',
);
globalThis[STORAGE_KEY] = globalThis[STORAGE_KEY] ?? new AsyncLocalStorage();
/** Express.js middleware that is responsible for initializing the context for each request. */
function middleware(req, res, next) {
const asyncLocalStorage = globalThis[STORAGE_KEY];
if (!asyncLocalStorage.getStore()) {
asyncLocalStorage.run(new Map(), () => next());
} else {
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) {
return globalThis[STORAGE_KEY].getStore()?.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 asyncLocalStorage = globalThis[STORAGE_KEY];
if (asyncLocalStorage.getStore()) {
asyncLocalStorage.getStore()?.set(key, value);
return value;
}
return undefined;
}
module.exports = {
middleware,
get: get,
set: set,
asyncLocalStorage: globalThis[STORAGE_KEY],
};