Skip to content

Instantly share code, notes, and snippets.

@imevro
Created April 27, 2017 08:41
Show Gist options
  • Save imevro/ade10ff8e3822610cc41d6cdbeeb4aa0 to your computer and use it in GitHub Desktop.
Save imevro/ade10ff8e3822610cc41d6cdbeeb4aa0 to your computer and use it in GitHub Desktop.
import { JSONToQueryParams } from '@dtrussia/utils.js';
const basicUrl = '/api/v1';
function checkStatus(response) {
if (response.status >= 200 && response.status < 300) {
return response;
}
const { status, body } = response;
const error = {
status,
body,
};
throw error;
}
const request = (method, resource, headers, body = null) =>
fetch(basicUrl + resource, {
method,
body,
mode: 'cors',
headers: {
'Content-Type': 'application/json',
},
}).then(checkStatus);
export function get(resource, params, headers) {
let path = resource;
if (params) {
const urlParams = encodeURI(JSONToQueryParams(params));
path = `${resource}?${urlParams}`;
}
return request('GET', path, headers);
}
export function post(resource, body, headers) {
return request('POST', resource, headers, JSON.stringify(body));
}
export function put(resource, body, headers) {
return request('PUT', resource, headers, JSON.stringify(body));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment