Skip to content

Instantly share code, notes, and snippets.

@hoIIer
Created April 6, 2020 23:25
Show Gist options
  • Save hoIIer/8a7cb968e6044f27216167d7a4bb2b33 to your computer and use it in GitHub Desktop.
Save hoIIer/8a7cb968e6044f27216167d7a4bb2b33 to your computer and use it in GitHub Desktop.
ember-fetch/ember-ajax compatible service
import Service, { inject as service } from '@ember/service';
import fetch, { Request } from 'fetch';
import config from 'ember-foo/config/environment';
export default class FetchService extends Service {
@service session;
headers() {
const headers = {};
const token = this.session.data.authenticated.token || config.token;
// authorization token.
headers.Authorization = `${config.tokenPrefix} ${token}`;
return headers;
}
async request(path, options={}) {
const url = `${config.api}/${config.namespace}/${path}`;
let response;
try {
response = await fetch(new Request(url, {
method: 'GET',
headers: this.headers(),
...options,
}));
} catch (err) {
throw new Error(err);
}
const json = await response.json();
if (response.ok) {
return json;
}
throw json;
}
post(url, data, options={}) {
return this.request(url, {
body: JSON.stringify(data),
method: 'POST',
...options,
});
}
}
@hoIIer
Copy link
Author

hoIIer commented Apr 6, 2020

example:

      @service fetch;
      ...
      try {
        await this.fetch.post('auth/register', {
          password: get('password'),
          username: get('username'),
        });
      } catch (err) {
        catchErrors(...);

        return undefined;
      }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment