1
1
'use strict' ;
2
2
3
3
const { AsyncLocalStorage } = require ( 'async_hooks' ) ;
4
- const asyncLocalStorage = new AsyncLocalStorage ( ) ;
4
+
5
+ const STORAGE_KEY = Symbol . for (
6
+ 'skonves/express-http-context/asyncLocalStorage' ,
7
+ ) ;
8
+
9
+ globalThis [ STORAGE_KEY ] = globalThis [ STORAGE_KEY ] ?? new AsyncLocalStorage ( ) ;
5
10
6
11
/** Express.js middleware that is responsible for initializing the context for each request. */
7
12
function middleware ( req , res , next ) {
13
+ const asyncLocalStorage = globalThis [ STORAGE_KEY ] ;
8
14
if ( ! asyncLocalStorage . getStore ( ) ) {
9
15
asyncLocalStorage . run ( new Map ( ) , ( ) => next ( ) ) ;
10
16
} else {
@@ -17,7 +23,7 @@ function middleware(req, res, next) {
17
23
* @param {string } key
18
24
*/
19
25
function get ( key ) {
20
- return asyncLocalStorage . getStore ( ) ?. get ( key ) ;
26
+ return globalThis [ STORAGE_KEY ] . getStore ( ) ?. get ( key ) ;
21
27
}
22
28
23
29
/**
@@ -26,6 +32,7 @@ function get(key) {
26
32
* @param {* } value
27
33
*/
28
34
function set ( key , value ) {
35
+ const asyncLocalStorage = globalThis [ STORAGE_KEY ] ;
29
36
if ( asyncLocalStorage . getStore ( ) ) {
30
37
asyncLocalStorage . getStore ( ) ?. set ( key , value ) ;
31
38
return value ;
@@ -37,5 +44,5 @@ module.exports = {
37
44
middleware,
38
45
get : get ,
39
46
set : set ,
40
- asyncLocalStorage
47
+ asyncLocalStorage : globalThis [ STORAGE_KEY ] ,
41
48
} ;
0 commit comments