diff --git a/packages/adapter/addon/-private/utils/fetch.ts b/packages/adapter/addon/-private/utils/fetch.ts index c59d4838f28..dd292082a08 100644 --- a/packages/adapter/addon/-private/utils/fetch.ts +++ b/packages/adapter/addon/-private/utils/fetch.ts @@ -2,19 +2,24 @@ import require, { has } from 'require'; type FetchFunction = (input: RequestInfo, init?: RequestInit | undefined) => Promise; -let _fetch: (() => FetchFunction) | null = null; +let _fetch: () => FetchFunction | null = null; -if (has('fetch')) { - // use `fetch` module by default, this is commonly provided by ember-fetch - let foundFetch = require('fetch').default; - _fetch = () => foundFetch; -} else if (typeof fetch === 'function') { - // fallback to using global fetch - _fetch = () => fetch; -} else { - throw new Error( - 'cannot find the `fetch` module or the `fetch` global. Did you mean to install the `ember-fetch` addon?' - ); -} +export default function getFetchFunction(): FetchFunction { + if (_fetch !== null) { + return _fetch(); + } -export default _fetch; + if (has('fetch')) { + // use `fetch` module by default, this is commonly provided by ember-fetch + let fetchFn = require('fetch').default; + _fetch = () => fetchFn; + } else if (typeof fetch === 'function') { + // fallback to using global fetch + _fetch = () => fetch; + } else { + throw new Error( + 'cannot find the `fetch` module or the `fetch` global. Did you mean to install the `ember-fetch` addon?' + ); + } + return _fetch(); +}