Skip to content

Commit

Permalink
lib: implement lazy loading for fetch function
Browse files Browse the repository at this point in the history
Instead of importing undici upfront, the module is now conditionally
required using require only when the fetch function is called for the
first time and the undici implementation is not already available. This
lazy loading approach improves resource usage and test reliability by
loading undici only when needed.
  • Loading branch information
YCChenVictor committed Apr 9, 2024
1 parent 3fdd4d3 commit 5c6a889
Showing 1 changed file with 7 additions and 5 deletions.
12 changes: 7 additions & 5 deletions lib/internal/bootstrap/web/exposed-window-or-worker.js
Original file line number Diff line number Diff line change
Expand Up @@ -57,17 +57,19 @@ defineReplaceableLazyAttribute(globalThis, 'perf_hooks', ['performance']);
const { installObjectURLMethods } = require('internal/url');
installObjectURLMethods();

let fetchImpl;
// https://fetch.spec.whatwg.org/#fetch-method
ObjectDefineProperty(globalThis, 'fetch', {
__proto__: null,
configurable: true,
enumerable: true,
writable: true,
value: function fetch(input, init = undefined) { // eslint-disable-line func-name-matching
// Loading undici alone lead to promises which breaks lots of tests so we
// have to load it really lazily for now.
const { fetch: impl } = require('internal/deps/undici/undici');
return impl(input, init);
value: function value(input, init = undefined) {
if (!fetchImpl) { // Implement lazy loading of undici module for fetch function
const undiciModule = require('internal/deps/undici/undici');
fetchImpl = undiciModule.fetch;
}
return fetchImpl(input, init);
},
});

Expand Down

0 comments on commit 5c6a889

Please sign in to comment.