11'use strict' ;
22
33const { 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 ( ) ;
510
611/** Express.js middleware that is responsible for initializing the context for each request. */
712function middleware ( req , res , next ) {
13+ const asyncLocalStorage = globalThis [ STORAGE_KEY ] ;
814 if ( ! asyncLocalStorage . getStore ( ) ) {
915 asyncLocalStorage . run ( new Map ( ) , ( ) => next ( ) ) ;
1016 } else {
@@ -17,7 +23,7 @@ function middleware(req, res, next) {
1723 * @param {string } key
1824 */
1925function get ( key ) {
20- return asyncLocalStorage . getStore ( ) ?. get ( key ) ;
26+ return globalThis [ STORAGE_KEY ] . getStore ( ) ?. get ( key ) ;
2127}
2228
2329/**
@@ -26,6 +32,7 @@ function get(key) {
2632 * @param {* } value
2733 */
2834function set ( key , value ) {
35+ const asyncLocalStorage = globalThis [ STORAGE_KEY ] ;
2936 if ( asyncLocalStorage . getStore ( ) ) {
3037 asyncLocalStorage . getStore ( ) ?. set ( key , value ) ;
3138 return value ;
@@ -37,5 +44,5 @@ module.exports = {
3744 middleware,
3845 get : get ,
3946 set : set ,
40- asyncLocalStorage
47+ asyncLocalStorage : globalThis [ STORAGE_KEY ] ,
4148} ;
0 commit comments