-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy pathutil.js
80 lines (71 loc) · 2.16 KB
/
util.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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
'use strict'
const isWrappedSymbol = Symbol('cls-rtracer-is-wrapped')
const wrappedSymbol = Symbol('cls-rtracer-wrapped-function')
function wrapEmitterMethod (emitter, method, wrapper) {
if (emitter[method][isWrappedSymbol]) {
return
}
const original = emitter[method]
const wrapped = wrapper(original)
wrapped[isWrappedSymbol] = true
emitter[method] = wrapped
return wrapped
}
const addMethods = [
'on',
'addListener',
'prependListener'
]
const removeMethods = [
'off',
'removeListener'
]
/**
* Wraps EventEmitter listener registration methods of the given emitter,
* so that all listeners are run in scope of the provided async resource.
*
* Supports registering same listener function to multiple events (or
* even the same one), as well as subsequent deregistering.
*/
function wrapEmitter (emitter, asyncResource) {
for (const method of addMethods) {
wrapEmitterMethod(emitter, method, (original) => function (event, handler) {
let wrapped = emitter[wrappedSymbol]
if (wrapped === undefined) {
wrapped = {}
emitter[wrappedSymbol] = wrapped
}
const wrappedHandler = asyncResource.runInAsyncScope.bind(asyncResource, handler, emitter)
const existing = wrapped[event]
if (existing === undefined) {
wrapped[event] = wrappedHandler
} else if (typeof existing === 'function') {
wrapped[event] = [existing, wrappedHandler]
} else {
wrapped[event].push(wrappedHandler)
}
return original.call(this, event, wrappedHandler)
})
}
for (const method of removeMethods) {
wrapEmitterMethod(emitter, method, (original) => function (event, handler) {
let wrappedHandler
const wrapped = emitter[wrappedSymbol]
if (wrapped !== undefined) {
const existing = wrapped[event]
if (existing !== undefined) {
if (typeof existing === 'function') {
wrappedHandler = existing
delete wrapped[event]
} else {
wrappedHandler = existing.pop()
}
}
}
return original.call(this, event, wrappedHandler || handler)
})
}
}
module.exports = {
wrapEmitter
}