accounts-frontend/src/services/request.js

63 lines
1.5 KiB
JavaScript
Raw Normal View History

2016-02-27 16:23:58 +05:30
function buildQuery(data) {
return Object.keys(data)
.map(
(keyName) =>
2016-02-23 11:27:16 +05:30
[keyName, typeof data[keyName] === 'undefined' ? '' : data[keyName]]
.map(encodeURIComponent)
.join('=')
)
.join('&')
;
}
2016-02-26 11:55:47 +05:30
let authToken;
2016-02-23 11:27:16 +05:30
const toJSON = (resp) => resp.json();
2016-02-26 11:55:47 +05:30
// if resp.success does not exist - degradating to HTTP status codes
const handleResponse = (resp) => Promise[resp.success || typeof resp.success === 'undefined' ? 'resolve' : 'reject'](resp);
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-02-23 11:27:16 +05:30
.then(toJSON)
.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
})
.then(toJSON)
.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;
}
};