From 939d4a31f751122193f2eee880e10172c8903d93 Mon Sep 17 00:00:00 2001 From: Vaidehi Joshi Date: Mon, 10 Jun 2019 14:53:17 -0700 Subject: [PATCH] Two small fixes to `fetch` 1. Don't ever assign the internal `fetch` to `null`. Instead, throw immediately if fetch is not found. 2. Don't extract the global fetch into module state. Instead, export a function that looks up the global fetch each time. This allows libraries that mock `fetch` to do so after Ember Data has already been loaded. --- packages/adapter/addon/-private/utils/fetch.ts | 15 +++++++++------ packages/adapter/addon/rest.js | 10 +++++++++- 2 files changed, 18 insertions(+), 7 deletions(-) diff --git a/packages/adapter/addon/-private/utils/fetch.ts b/packages/adapter/addon/-private/utils/fetch.ts index 1be5259f483..c59d4838f28 100644 --- a/packages/adapter/addon/-private/utils/fetch.ts +++ b/packages/adapter/addon/-private/utils/fetch.ts @@ -1,17 +1,20 @@ import require, { has } from 'require'; -type MaybeFetch = { - (input: RequestInfo, init?: RequestInit | undefined): Promise; -} | null; +type FetchFunction = (input: RequestInfo, init?: RequestInit | undefined) => Promise; -let _fetch: MaybeFetch = null; +let _fetch: (() => FetchFunction) | null = null; if (has('fetch')) { // use `fetch` module by default, this is commonly provided by ember-fetch - _fetch = require('fetch').default; + let foundFetch = require('fetch').default; + _fetch = () => foundFetch; } else if (typeof fetch === 'function') { // fallback to using global fetch - _fetch = 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 _fetch; diff --git a/packages/adapter/addon/rest.js b/packages/adapter/addon/rest.js index f205f57e7b4..53f7f9afc03 100644 --- a/packages/adapter/addon/rest.js +++ b/packages/adapter/addon/rest.js @@ -1057,7 +1057,15 @@ const RESTAdapter = Adapter.extend(BuildURLMixin, { }, _fetchRequest(options) { - return fetch(options.url, options); + let fetchFunction = fetch(); + + if (fetchFunction) { + return fetchFunction(options.url, options); + } else { + throw new Error( + 'cannot find the `fetch` module or the `fetch` global. Did you mean to install the `ember-fetch` addon?' + ); + } }, _ajax(options) {