@@ -6,22 +6,36 @@ const globalDispatcher = Symbol.for('undici.globalDispatcher.1')
6
6
const { InvalidArgumentError } = require ( './core/errors' )
7
7
const Agent = require ( './dispatcher/agent' )
8
8
9
- if ( getGlobalDispatcher ( ) === undefined ) {
10
- setGlobalDispatcher ( new Agent ( ) )
11
- }
9
+ let currentDispatcher = null
12
10
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
16
15
}
16
+ } else {
17
17
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
+ } ,
20
27
enumerable : false ,
21
28
configurable : false
22
29
} )
23
30
}
24
31
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
+
25
39
function getGlobalDispatcher ( ) {
26
40
return globalThis [ globalDispatcher ]
27
41
}
0 commit comments