const TIME_OUT = 6000;
const TOKEN = 'token';
const ContentType = {
json:'application/json;charset=UTF-8',
form: 'application/x-www-form-urlencoded; charset=UTF-8',
download: 'application/octet-stream'
};
function baseFetch(url, options) {
const baseOptions = {
method: "GET",
headers: {
"Content-type": ContentType.json
},
credentials: 'include'
};
options = Object.assign(baseOptions, options);
const {method, body} = options;
if (method === 'GET' && Object.isObject(body)) {
const paramsArray = [];
Object.keys(body).forEach((key) =>
paramsArray.push(key + "=" + encodeURIComponent(body[key]))
);
if (url.search(/\?/) === -1) {
url += "?" + paramsArray.join("&");
} else {
url += "&" + paramsArray.join("&");
}
delete options.body;
}
const token = localStorage.getItem(TOKEN);
if (token) options.headers["TOKEN"] = token;
return Promise.race([
new Promise((resolve, reject) => {
setTimeout(() => {
reject(new Error('request timeout'));
}, TIME_OUT);
}),
new Promise((resolve, reject) => {
window.fetch(url, options)
.then(async res => {
if(!/^(2|3)\d{2}$/.test(res.status)) {
switch(res.status) {
case 401:
break
case 403:
localStorage.removeItem(TOKEN)
break
case 404:
break
}
return Promise.reject(res)
}
if (res.headers['set-cookies']) {
localStorage.setItem(TOKEN, res.headers['set-cookies']);
}
const data = options.headers['Content-type'] === ContentType.download ? res.blob() : res.json();
resolve(data);
})
.catch(err => {
reject(err);
});
})
])
}
export const fetchGet = (url, params) => {
return baseFetch(url, {body: params});
}
export const fetchPost = (url, params) => {
return baseFetch(url, {method: 'POST', body: JSON.stringify(params)});
}
export const fetchDownload = (url, params) => {
return baseFetch(url, {
method: 'POST',
body: JSON.stringify(params),
headers: {
"Content-type": ContentType.download
}
});
}