Skip to content

Commit

Permalink
Two small fixes to fetch
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
vaidehijoshi authored and wycats committed Jun 10, 2019
1 parent 6e04daf commit 939d4a3
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 7 deletions.
15 changes: 9 additions & 6 deletions packages/adapter/addon/-private/utils/fetch.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,20 @@
import require, { has } from 'require';

type MaybeFetch = {
(input: RequestInfo, init?: RequestInit | undefined): Promise<Response>;
} | null;
type FetchFunction = (input: RequestInfo, init?: RequestInit | undefined) => Promise<Response>;

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;
10 changes: 9 additions & 1 deletion packages/adapter/addon/rest.js
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down

0 comments on commit 939d4a3

Please sign in to comment.