2016-02-13 20:58:47 +05:30
|
|
|
function serialize(data) {
|
|
|
|
return Object.keys(data)
|
|
|
|
.map(
|
|
|
|
(keyName) =>
|
2016-02-23 11:27:16 +05:30
|
|
|
[keyName, typeof data[keyName] === 'undefined' ? '' : data[keyName]]
|
2016-02-13 20:58:47 +05:30
|
|
|
.map(encodeURIComponent)
|
|
|
|
.join('=')
|
|
|
|
)
|
|
|
|
.join('&')
|
|
|
|
;
|
|
|
|
}
|
|
|
|
|
2016-02-23 11:27:16 +05:30
|
|
|
const toJSON = (resp) => resp.json();
|
|
|
|
const handleResponse = (resp) => Promise[resp.success ? 'resolve' : 'reject'](resp);
|
|
|
|
|
2016-02-13 20:58:47 +05:30
|
|
|
export default {
|
|
|
|
post(url, data) {
|
|
|
|
return fetch(url, {
|
|
|
|
method: 'POST',
|
|
|
|
headers: {
|
|
|
|
Accept: 'application/json',
|
|
|
|
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
|
|
|
|
},
|
|
|
|
body: serialize(data)
|
|
|
|
})
|
2016-02-23 11:27:16 +05:30
|
|
|
.then(toJSON)
|
|
|
|
.then(handleResponse)
|
|
|
|
;
|
|
|
|
},
|
|
|
|
get(url, data) {
|
|
|
|
if (typeof data === 'object') {
|
|
|
|
const separator = url.indexOf('?') === -1 ? '?' : '&';
|
|
|
|
url += separator + serialize(data);
|
|
|
|
}
|
|
|
|
|
|
|
|
return fetch(url, {
|
|
|
|
headers: {
|
|
|
|
Accept: 'application/json'
|
|
|
|
}
|
|
|
|
})
|
|
|
|
.then(toJSON)
|
|
|
|
.then(handleResponse)
|
2016-02-13 20:58:47 +05:30
|
|
|
;
|
|
|
|
}
|
|
|
|
};
|