Created
October 14, 2015 09:26
-
-
Save frontenddeveloping/48b00f7693da202279b7 to your computer and use it in GitHub Desktop.
Simple fetch API wrapper
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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