accounts-frontend/src/services/request.js

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