Revert "try to use lightweight unfetch instead of heavy axious"

This reverts commit b020ef2
This commit is contained in:
igoradamenko
2018-03-10 23:07:01 +03:00
parent cd82d08dbc
commit 1aa699ebd3
4 changed files with 38 additions and 30 deletions
+36 -23
View File
@@ -1,8 +1,7 @@
import 'common/promises';
// TODO: i think we need to use unfetch here instead of heavy axios
// import axios from 'axios';
import fetch from 'unfetch';
import axios from 'axios';
import { BASE_URL, API_BASE } from './constants';
import { siteId } from './settings';
@@ -10,16 +9,16 @@ import { siteId } from './settings';
const fetcher = {};
const methods = ['get', 'post', 'put', 'patch', 'delete', 'head'];
// const { CancelToken } = axios;
// let cancelHandler = [];
const { CancelToken } = axios;
let cancelHandler = [];
// fetcher.cancel = (mask) => {
// cancelHandler.forEach(req => {
// if (req.url.includes(mask)) {
// req.executor('Operation canceled by the user.');
// }
// });
// };
fetcher.cancel = (mask) => {
cancelHandler.forEach(req => {
if (req.url.includes(mask)) {
req.executor('Operation canceled by the user.');
}
});
};
methods.forEach(method => {
fetcher[method] = data => {
@@ -32,26 +31,40 @@ methods.forEach(method => {
const basename = `${BASE_URL}${overriddenApiBase}`;
return new Promise((resolve, reject) => {
const headers = {
Accept: 'application/json',
'Content-Type': 'application/json',
};
const parameters = {
method: method.toUpperCase(),
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
credentials: withCredentials && 'include',
method,
headers,
withCredentials,
};
if (Object.keys(body).length) {
parameters.data = body;
}
let requestUrl = `${basename}${url}`;
if (method !== 'post') requestUrl += (requestUrl.includes('?') ? '&' : '?') + `site=${siteId}`; // TODO: rewrite it
parameters.url = `${basename}${url}`;
if (method !== 'post') parameters.url += (parameters.url.includes('?') ? '&' : '?') + `site=${siteId}`;
parameters.cancelToken = new CancelToken(executor => {
cancelHandler.push({
executor,
url: parameters.url,
});
});
fetch(requestUrl, parameters)
.then(res => res.json())
.then(data => resolve(data))
.catch(error => reject(error));
axios(parameters)
.then(res => resolve(res.data))
.catch(error => {
if (!axios.isCancel(error)) {
reject(error);
}
})
.finally(() => {
cancelHandler = cancelHandler.filter(req => req.url !== parameters.url);
});
});
}
});