-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathals.ts
26 lines (21 loc) · 780 Bytes
/
als.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
import { AsyncLocalStorage } from 'async_hooks'
import { AsynchronousLocalStorage, StorageType } from './als-types'
const asyncLocalStorage = new AsyncLocalStorage<StorageType>()
export const als: AsynchronousLocalStorage = {
storageImplementation: 'AsyncLocalStorage',
get: <T>(key: string): T | undefined => {
const store = asyncLocalStorage.getStore()
return store?.get(key)
},
set: <T>(key: string, value: T): void => {
const store = asyncLocalStorage.getStore()
store?.set(key, value)
},
runWith: (callback: () => void, defaults?: Record<string, any>): void => {
const store: StorageType = defaults ? new Map(Object.entries(defaults)) : new Map()
asyncLocalStorage.run(store, () => {
callback()
})
},
}
export default als