Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Simple fetch API wrapper
(function(global) {
'use strict';
var JSON_TYPE_NAME = 'type';
function getQueryString(queryParams) {
var params = Object.keys(queryParams).map(function(paramName) {
return [paramName, encodeURIComponent(queryParams[paramName])].join('=');
});
return '?' + params.join('&');
}
function checkStatus(response) {
if (response.status >= 200 && response.status < 300 || response.status === 304) {
return Promise.resolve(response);
} else {
var error = new Error(response.statusText || response.status);
error.response = response;
return Promise.reject(error);
}
}
function setHeaders(headers) {
headers = headers || {};
headers['X-Requested-With'] = 'XMLHttpRequest';
return headers;
}
function setCredentials(options) {
options = options || {};
if (!options.credentials) {
options.credentials = 'same-origin';
}
return options;
}
function toJson(response) {
return response.json();
}
function toText(response) {
return response.text();
}
function fetchMain(method, url, data, options, type) {
var responseAs = toText;
options = options || {};
type = type || JSON_TYPE_NAME;
options.method = method;
options.headers = setHeaders(options.headers);
if (type === JSON_TYPE_NAME) {
responseAs = toJson;
options.headers.Accept = 'application/json';
}
if (method === 'get') {
url += getQueryString(data);
} else {
options.body = data;
}
return global.fetch(url, setCredentials(options)).then(checkStatus).then(responseAs);
}
function getFetch(url, data, options, type) {
return fetchMain('get', url, data, options, type);
}
function postFetch(url, data, options, type) {
return fetchMain('post', url, data, options, type);
}
global.fetchWrapper = {
get: getFetch,
post: postFetch
};
}(window));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment