83 lines
1.9 KiB
JavaScript
Raw Normal View History

function convertQueryValue(value) {
if (typeof value === 'undefined') {
return '';
}
if (value === true) {
return 1;
}
if (value === false) {
return 0;
}
return value;
}
function buildQuery(data = {}) {
return Object.keys(data)
.map(
(keyName) =>
[keyName, convertQueryValue(data[keyName])]
.map(encodeURIComponent)
.join('=')
)
.join('&')
;
}
2016-02-26 08:25:47 +02:00
let authToken;
2016-03-01 22:36:14 +02:00
const checkStatus = (resp) => Promise[resp.status >= 200 && resp.status < 300 ? 'resolve' : 'reject'](resp);
2016-02-23 07:57:16 +02:00
const toJSON = (resp) => resp.json();
2016-03-01 22:36:14 +02:00
const rejectWithJSON = (resp) => toJSON(resp).then((resp) => {throw resp;});
2016-02-26 08:25:47 +02:00
const handleResponse = (resp) => Promise[resp.success || typeof resp.success === 'undefined' ? 'resolve' : 'reject'](resp);
2016-03-01 22:36:14 +02:00
2016-02-26 08:25:47 +02:00
const getDefaultHeaders = () => {
const header = {Accept: 'application/json'};
if (authToken) {
header.Authorization = `Bearer ${authToken}`;
}
return header;
};
2016-02-23 07:57:16 +02:00
export default {
post(url, data) {
return fetch(url, {
method: 'POST',
headers: {
2016-02-26 08:25:47 +02:00
...getDefaultHeaders(),
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
},
2016-02-27 12:53:58 +02:00
body: buildQuery(data)
})
2016-03-01 22:36:14 +02:00
.then(checkStatus)
.then(toJSON, rejectWithJSON)
2016-02-23 07:57:16 +02:00
.then(handleResponse)
;
},
2016-02-26 08:25:47 +02:00
2016-02-23 07:57:16 +02:00
get(url, data) {
if (typeof data === 'object') {
const separator = url.indexOf('?') === -1 ? '?' : '&';
2016-02-27 12:53:58 +02:00
url += separator + buildQuery(data);
2016-02-23 07:57:16 +02:00
}
return fetch(url, {
2016-02-26 08:25:47 +02:00
headers: getDefaultHeaders()
2016-02-23 07:57:16 +02:00
})
2016-03-01 22:36:14 +02:00
.then(checkStatus)
.then(toJSON, rejectWithJSON)
2016-02-23 07:57:16 +02:00
.then(handleResponse)
;
2016-02-26 08:25:47 +02:00
},
2016-02-27 12:53:58 +02:00
buildQuery,
2016-02-26 08:25:47 +02:00
setAuthToken(tkn) {
authToken = tkn;
}
};