Skip to content

Commit 84533e6

Browse files
committed
fix: avoid setup global dispatcher in advance
1 parent c3f5591 commit 84533e6

File tree

1 file changed

+22
-8
lines changed

1 file changed

+22
-8
lines changed

lib/global.js

Lines changed: 22 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -6,22 +6,36 @@ const globalDispatcher = Symbol.for('undici.globalDispatcher.1')
66
const { InvalidArgumentError } = require('./core/errors')
77
const Agent = require('./dispatcher/agent')
88

9-
if (getGlobalDispatcher() === undefined) {
10-
setGlobalDispatcher(new Agent())
11-
}
9+
let currentDispatcher = null
1210

13-
function setGlobalDispatcher (agent) {
14-
if (!agent || typeof agent.dispatch !== 'function') {
15-
throw new InvalidArgumentError('Argument agent must implement Agent')
11+
if (Object.hasOwn(globalThis, globalDispatcher)) {
12+
const existing = Reflect.get(globalThis, globalDispatcher)
13+
if (existing && typeof existing.dispatch === 'function') {
14+
currentDispatcher = existing
1615
}
16+
} else {
1717
Object.defineProperty(globalThis, globalDispatcher, {
18-
value: agent,
19-
writable: true,
18+
get () {
19+
if (currentDispatcher === null) {
20+
currentDispatcher = new Agent()
21+
}
22+
return currentDispatcher
23+
},
24+
set (agent) {
25+
setGlobalDispatcher(agent)
26+
},
2027
enumerable: false,
2128
configurable: false
2229
})
2330
}
2431

32+
function setGlobalDispatcher (agent) {
33+
if (!agent || typeof agent.dispatch !== 'function') {
34+
throw new InvalidArgumentError('Argument agent must implement Agent')
35+
}
36+
currentDispatcher = agent
37+
}
38+
2539
function getGlobalDispatcher () {
2640
return globalThis[globalDispatcher]
2741
}

0 commit comments

Comments
 (0)