Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve fetch #6155

Merged
merged 1 commit into from
Jun 13, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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?'
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice touch, thank you for adding this!

);
}

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?'
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we need the same error in both places? What does that buy us?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I wasn't sure which of the two we should do. At first glance, I'd prefer it to happen at the top level.

);
}
},

_ajax(options) {
Expand Down