import tool from './tool';
import qs from 'qs';
let baseURL = '',
env = process.env.NODE_ENV || 'development',
inital = {
method: 'GET',
params: null,
body: null,
headers: {},
cache: 'no-cache',
credentials: 'include',
responseType: 'JSON'
};
switch (env) {
case 'development':
baseURL = 'http://127.0.0.1:9999';
break;
case 'production':
baseURL = 'http://api.zhufengpeixun.cn';
break;
}
export default function request(url, config) {
if (typeof url !== 'string') throw new TypeError('url must be required and of string type');
if (!tool.isPlainObject(config)) config = {};
config = tool.merge(true, {}, inital, config);
let {
method,
params,
body,
headers,
cache,
credentials,
responseType
} = config;
if (!/^http(s?):\/\//i.test(url)) url = baseURL + url;
if (params != null) {
if (tool.isPlainObject(params)) params = qs.stringify(params);
url += `${url.includes('?')?'&':'?'}${params}`;
}
if (tool.isPlainObject(body)) {
headers['Content-Type'] = 'application/x-www-form-urlencoded';
body = qs.stringify(body);
} else if (typeof body === 'string') {
try {
body = JSON.parse(body);
headers['Content-Type'] = 'application/json';
} catch (err) {
headers['Content-Type'] = 'application/x-www-form-urlencoded';
}
}
let token = localStorage.getItem('token');
if (token) headers['Authorization'] = token;
config = {
method: method.toUpperCase(),
headers,
credentials,
cache
};
if (/^(POST|PUT|PATCH)$/i.test(method) && body != null) config.body = body;
return fetch(url, config).then(response => {
let {
status,
statusText
} = response;
if (status >= 200 && status < 400) {
let result;
switch (responseType.toUpperCase()) {
case 'JSON':
result = response.json();
break;
case 'TEXT':
result = response.text();
break;
case 'BLOB':
result = response.blob();
break;
case 'ARRAYBUFFER':
result = response.arrayBuffer();
break;
}
return result;
}
return Promise.reject({
code: 'STATUS ERROR',
status,
statusText
});
}).catch(reason => {
if (reason && reason.code === 'STATUS ERROR') {
switch (reason.status) {
case 400:
break;
case 401:
break;
case 404:
break;
}
} else if (!navigator.onLine) {
} else {
}
return Promise.reject(reason);
});
};