@@ -6,22 +6,36 @@ const globalDispatcher = Symbol.for('undici.globalDispatcher.1')
66const { InvalidArgumentError } = require ( './core/errors' )
77const 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+
2539function getGlobalDispatcher ( ) {
2640 return globalThis [ globalDispatcher ]
2741}
0 commit comments