Skip to content

Commit

Permalink
lazy-load undici
Browse files Browse the repository at this point in the history
  • Loading branch information
targos committed Feb 19, 2022
1 parent 92594d6 commit 7d96d08
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 8 deletions.
38 changes: 31 additions & 7 deletions lib/internal/bootstrap/pre_execution.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

const {
NumberParseInt,
ObjectDefineProperties,
ObjectDefineProperty,
ObjectGetOwnPropertyDescriptor,
SafeMap,
Expand Down Expand Up @@ -156,18 +157,41 @@ function setupFetch() {
return;
}

const undici = require('internal/deps/undici/undici');
let undici;
function lazyUndici() {
if (undici) {
return undici;
}

emitExperimentalWarning('The Fetch API');
undici = require('internal/deps/undici/undici');
}

async function fetch(input, init = undefined) {
emitExperimentalWarning('Fetch');
return undici.fetch(input, init);
return lazyUndici().fetch(input, init);
}

defineOperation(globalThis, 'fetch', fetch);
exposeInterface(globalThis, 'FormData', undici.FormData);
exposeInterface(globalThis, 'Headers', undici.Headers);
exposeInterface(globalThis, 'Request', undici.Request);
exposeInterface(globalThis, 'Response', undici.Response);

function lazyInterface(name) {
return {
configurable: true,
enumerable: false,
get() {
return lazyUndici()[name];
},
set(value) {
exposeInterface(globalThis, name, value);
}
};
}

ObjectDefineProperties(globalThis, {
FormData: lazyInterface('FormData'),
Headers: lazyInterface('Headers'),
Request: lazyInterface('Request'),
Response: lazyInterface('Response'),
});
}

// TODO(aduh95): move this to internal/bootstrap/browser when the CLI flag is
Expand Down
2 changes: 1 addition & 1 deletion test/parallel/test-fetch.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ assert.strictEqual(typeof globalThis.Response, 'function');

common.expectWarning(
'ExperimentalWarning',
'Fetch is an experimental feature. This feature could change at any time'
'The Fetch API is an experimental feature. This feature could change at any time'
);

const server = http.createServer((req, res) => {
Expand Down

0 comments on commit 7d96d08

Please sign in to comment.