Skip to content

Instantly share code, notes, and snippets.

@aboekhoff
Created January 21, 2016 22:13
Show Gist options
  • Save aboekhoff/382f0d7cfc1ef7fb0df8 to your computer and use it in GitHub Desktop.
Save aboekhoff/382f0d7cfc1ef7fb0df8 to your computer and use it in GitHub Desktop.
import { getAccessToken } from './session';
// quick and dirty serializer
function serializeObjectToQueryString(obj) {
if (!obj) { return ""; }
const str = [];
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
str.push(encodeURIComponent(prop) + "=" + encodeURIComponent(obj[prop]));
}
}
return '?' + str.join("&");
}
const successHandler = (success, failure) => response => {
if (response.status >= 200 && response.status < 300) {
return response.json().then(json => {
if (success) {
success(json)
}
})
} else {
return response.json().then(json => {
const error = new Error(response.statusText)
error.type = response.status
error.json = json
if (failure) {
failure(error);
} else {
throw error;
}
})
}
}
const errorHandler = failure => response => {
failure(response)
}
// data is any data to be sent in body or query string
// success is callback for success status codes
// failure is callback for error status codes
// error is callback for network errors
const defaultOptions = {
data: null,
success: null,
failure: null,
error: null
}
function get(url, options=defaultOptions) {
return fetch(url + serializeObjectToQueryString(options.data), {
method: 'get',
headers: {
'Authorization': getAccessToken()
}
})
.then(successHandler(options.success, options.failure))
.catch(errorHandler(options.error || options.failure))
}
function post(url, options=defaultOptions) {
return fetch(url, {
method: 'post',
headers: {
'Authorization': getAccessToken(),
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(options.data)
})
.then(successHandler(options.success, options.failure))
.catch(errorHandler(options.error || options.failure))
}
export default { get, post }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment