Skip to content

Instantly share code, notes, and snippets.

@sjmueller
Created October 24, 2015 19:34
Show Gist options
  • Save sjmueller/8d07e7b81832d6ede068 to your computer and use it in GitHub Desktop.
Save sjmueller/8d07e7b81832d6ede068 to your computer and use it in GitHub Desktop.
http util using fetch
// add fetch import here.
const baseUrl = `http://localhost:8888/api/`;
class ResponseError extends Error {
constructor(messages) {
super();
this.messages = messages;
}
}
async function checkStatus(response) {
if (response.status >= 200 && response.status < 300) {
return response;
}
// extract error(s) and throw
let body;
if (response.status === 422) {
body = (await response.json()).errors;
} else {
body = await response.text();
}
throw new ResponseError(body);
}
export async function get(resource) {
const response = await fetch(baseUrl + resource);
await checkStatus(response);
return response.json();
}
export async function post(resource, body) {
const options = {
method: 'post',
headers: {
'Content-Type': 'application/json'
}
};
if (body) {
options.body = JSON.stringify(body);
}
const response = await fetch(baseUrl + resource, options);
await checkStatus(response);
const text = await response.text();
return text && JSON.parse(text);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment