Skip to content

Instantly share code, notes, and snippets.

@vittoriozamboni
Created July 15, 2019 19:42
Show Gist options
  • Save vittoriozamboni/c0cea9ad4a1a1aa6f7d10aedf4087562 to your computer and use it in GitHub Desktop.
Save vittoriozamboni/c0cea9ad4a1a1aa6f7d10aedf4087562 to your computer and use it in GitHub Desktop.
Request
export const METHODS = {
GET: 'GET',
POST: 'POST',
PATCH: 'PATCH',
PUT: 'PUT',
DELETE: 'DELETE'
};
let commonHeaders = {};
export function setCommonHeaders(common) {
commonHeaders = { ...common };
}
export function getCommonHeaders() {
return { ...commonHeaders };
}
export default function request(
url,
{ payload, method = METHODS.GET, headers = {}, body, extraOptions = {} } = {}
) {
const params = {
method,
headers: { ...getCommonHeaders(), ...headers },
mode: 'cors',
cache: 'no-cache',
credentials: 'same-origin',
redirect: 'follow',
referrer: 'no-referrer',
...extraOptions
};
if (body) {
params.body = body;
} else if (payload) {
// Set auto header to JSON
if (!params.headers['Content-Type']) {
params.headers['Content-Type'] = 'application/json';
}
params.body = JSON.stringify(payload);
}
const requestUrl = url.indexOf('http://') >= 0 || url.indexOf('https://') >= 0 ? url : `${BACKEND_URL}${url}`;
console.log(`Request [${params.method}]: `, url, params);
return fetch(requestUrl, params)
.then(response => {
console.log('Request: response to ', url, response);
if (!response.ok) {
console.error('Request: Invalid!', response.status, response.statusText);
throw new Error(response);
}
return response.status !== 204 ? response.json() : true;
})
.catch(error => {
console.error('Error during fetch: ', error);
throw new Error(error);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment