-
Notifications
You must be signed in to change notification settings - Fork 4
/
cls-fallback.ts
33 lines (29 loc) · 849 Bytes
/
cls-fallback.ts
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
import { createNamespace } from 'cls-hooked'
import { AsynchronousLocalStorage } from './als-types'
const _namespace = createNamespace('@kibertoad/als')
export const cls: AsynchronousLocalStorage = {
storageImplementation: 'cls-hooked',
get: <T>(key: string): T | undefined => {
if (_namespace.active) {
return _namespace.get(key)
}
return undefined
},
set: <T>(key: string, value: T) => {
if (_namespace.active) {
_namespace.set(key, value)
}
},
runWith: (callback: () => void, defaults?: Record<string, any>) => {
_namespace.run(() => {
if (defaults) {
const objectKeys = Object.keys(defaults)
for (let i = 0; i < objectKeys.length; i++) {
_namespace.set(objectKeys[i], defaults[objectKeys[i]])
}
}
callback()
})
},
}
export default cls