Created
August 27, 2015 02:00
-
-
Save maddie927/9f9d7a406530186493a8 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
import 'isomorphic-fetch'; | |
const getOkAndJsonBody = res => { | |
return res.text().then(text => { | |
try { | |
return {ok:res.ok,body: text && JSON.parse(text) || {}}; | |
} catch (err) { | |
return {ok:res.ok,body:{}}; | |
} | |
}); | |
}; | |
const checkOk = res => res.ok ? res : Promise.reject(res); | |
const unwrapBody = res => res.body; | |
export const fetchJson = (url, options = {}, overrideMethod) => { | |
if (overrideMethod) options.method = overrideMethod; | |
if (!options.headers) options.headers = {}; | |
options.credentials = 'same-origin'; | |
options.headers['Accept'] = 'application/json'; | |
if (options.body) { | |
options.headers['Content-Type'] = 'application/json'; | |
if (typeof options.body !== 'string') { | |
options.body = JSON.stringify(options.body); | |
} | |
} | |
return fetch(url, options) | |
.then(getOkAndJsonBody) | |
.then(checkOk) | |
.then(unwrapBody); | |
}; | |
export const getJson = (url, options) => fetchJson(url, options, 'GET'); | |
export const postJson = (url, options) => fetchJson(url, options, 'POST'); | |
export const putJson = (url, options) => fetchJson(url, options, 'PUT'); | |
export const deleteJson = (url, options) => fetchJson(url, options, 'DELETE'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment