-
Notifications
You must be signed in to change notification settings - Fork 57
Expand file tree
/
Copy pathcontext.js
More file actions
54 lines (46 loc) · 1.28 KB
/
context.js
File metadata and controls
54 lines (46 loc) · 1.28 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
49
50
51
52
53
54
import { AsyncLocalStorage } from 'async_hooks'
const internalContext = {}
const contextProxyHandler = {
set(target, name, value, receiver) {
const currentContext = asyncLocalStorage.getStore()
if (currentContext) {
currentContext[name] = value
return true
} else {
return Reflect.set(target, name, value, receiver)
}
},
get(target, name, receiver) {
const currentContext = asyncLocalStorage.getStore()
if (currentContext) {
return currentContext[name]
} else {
return Reflect.get(target, name, receiver)
}
}
}
const context = new Proxy(internalContext, contextProxyHandler)
const asyncLocalStorage = new AsyncLocalStorage()
export function generateContext(temporary) {
if(temporary) {
Object.assign(context, temporary)
}
return context
}
export function generateCurrentContext(temporary, callback) {
const currentContext = {...internalContext, ...temporary}
asyncLocalStorage.run(currentContext, () => {
callback(currentContext);
});
}
export function getCurrentContext(temporary) {
const currentContext = asyncLocalStorage.getStore()
if (!currentContext) {
return generateContext()
}
if(temporary) {
Object.assign(currentContext, temporary)
}
return currentContext
}
export default context