2016-02-27 16:28:29 +05:30
|
|
|
function convertQueryValue(value) {
|
|
|
|
if (typeof value === 'undefined') {
|
|
|
|
return '';
|
|
|
|
}
|
|
|
|
|
|
|
|
if (value === true) {
|
|
|
|
return 1;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (value === false) {
|
|
|
|
return 0;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-02-27 16:23:58 +05:30
|
|
|
function buildQuery(data) {
|
2016-02-13 20:58:47 +05:30
|
|
|
return Object.keys(data)
|
|
|
|
.map(
|
|
|
|
(keyName) =>
|
2016-02-27 16:28:29 +05:30
|
|
|
[keyName, convertQueryValue(data[keyName])]
|
2016-02-13 20:58:47 +05:30
|
|
|
.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
|
|
|
|
2016-02-13 20:58:47 +05:30
|
|
|
export default {
|
|
|
|
post(url, data) {
|
|
|
|
return fetch(url, {
|
|
|
|
method: 'POST',
|
|
|
|
headers: {
|
2016-02-26 11:55:47 +05:30
|
|
|
...getDefaultHeaders(),
|
2016-02-13 20:58:47 +05:30
|
|
|
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
|
|
|
|
},
|
2016-02-27 16:23:58 +05:30
|
|
|
body: buildQuery(data)
|
2016-02-13 20:58:47 +05:30
|
|
|
})
|
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-13 20:58:47 +05:30
|
|
|
;
|
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;
|
2016-02-13 20:58:47 +05:30
|
|
|
}
|
|
|
|
};
|