-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathasyncforge.js
63 lines (49 loc) · 1.18 KB
/
asyncforge.js
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
55
56
57
58
59
60
61
62
63
'use strict'
const { AsyncLocalStorage } = require('node:async_hooks')
const asyncLocalStorage = new AsyncLocalStorage()
class Store {
#internal
constructor (internal) {
this.#internal = internal
}
run (fn) {
return asyncLocalStorage.run(this.#internal, fn)
}
enterWith () {
asyncLocalStorage.enterWith(this.#internal)
}
}
function create (fn) {
const store = new Store(Object.create(null))
if (fn) {
store.run(fn)
}
return store
}
let memoCounter = 0
function memo (name) {
name = name || 'memo' + memoCounter++
const sym = Symbol('memo.' + name)
function get () {
const store = asyncLocalStorage.getStore()
if (!store) {
throw new Error('asyncforge store has not been created')
}
return store[sym]
}
function set (value) {
const store = asyncLocalStorage.getStore()
if (!store) {
throw new Error('asyncforge store has not been created')
}
if (Object.hasOwnProperty.call(store, sym)) {
throw new Error(`asyncforge store already initialized for ${name}`)
}
store[sym] = value
}
get.set = set
get.key = sym
return get
}
module.exports.create = create
module.exports.memo = memo