-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnamespace.js
More file actions
112 lines (97 loc) · 2.38 KB
/
namespace.js
File metadata and controls
112 lines (97 loc) · 2.38 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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
const { createHook, executionAsyncId } = require('async_hooks')
const { Context } = require('./context')
class Namespace {
constructor (name) {
this.name = name
this.contextsByAsyncId = new Map()
this._hook = createHook({
init: this._init.bind(this),
before: this._before.bind(this),
after: this._after.bind(this),
destroy: this._destroy.bind(this)
})
this._currentContext = null
this._hook.enable()
}
/**
* Get value for a given key from the Namespace
* @param {String} key
* @returns {Any}
*/
get (key) {
if (!this._currentContext) return null
return this._currentContext.store.get(key)
}
/**
* Set value for a given key into the Namespace
* @param {String} key
* @param {Any} value
* @returns {Any}
*/
set (key, value) {
if (!this._currentContext) return null
this._currentContext.store.set(key, value)
return value
}
/**
* Init context
* @returns {Context}
*/
initContext () {
const asyncId = executionAsyncId()
const context = new Context(this, asyncId)
this.contextsByAsyncId.set(asyncId, context)
this._currentContext = context
return context
}
/**
* Private: init function used by the Hook
* @param {String} asyncId
* @param {Any} type
* @param {Any} triggerId
* @param {Any} resource
*/
_init (asyncId, type, triggerId) {
const context = this.contextsByAsyncId.get(triggerId)
if (context) {
this._currentContext = context
this.contextsByAsyncId.set(asyncId, context)
context.asyncIds.add(asyncId)
}
}
/**
* Private: before function used by the Hook
* @param {String} asyncId
*/
_before (asyncId) {
const context = this.contextsByAsyncId.get(asyncId)
if (context) {
this._currentContext = context
}
}
/**
* Private: after function used by the Hook
* @param {String} asyncId
*/
_after (asyncId) {
const context = this.contextsByAsyncId.get(asyncId)
if (context) {
this._currentContext = context
}
}
/**
* Private: destroy function used by the Hook
* @param {String} asyncId
*/
_destroy (asyncId) {
const context = this.contextsByAsyncId.get(asyncId)
if (context) {
this._currentContext = context
context.asyncIds.delete(asyncId)
this.contextsByAsyncId.delete(asyncId)
}
}
}
module.exports = {
Namespace
}