You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
90 lines
2.0 KiB
JavaScript
90 lines
2.0 KiB
JavaScript
const configDefault = {
|
|
showError: true,
|
|
canEmpty: false,
|
|
returnOrigin: false,
|
|
withoutCheck: false,
|
|
mock: false,
|
|
timeout: 10000,
|
|
responseType: 'json',
|
|
// credentials: 'include',
|
|
};
|
|
function request(method, path, data, config) {
|
|
const myInit = {
|
|
...configDefault,
|
|
...config,
|
|
method,
|
|
// body: JSON.stringify(data),
|
|
body: (data),
|
|
};
|
|
if (method === 'GET') {
|
|
let params = '';
|
|
let ifp = '';
|
|
if (data) {
|
|
// 对象转url参数
|
|
params = new URLSearchParams(data).toString();
|
|
ifp = params ? '?' : ifp;
|
|
}
|
|
ifp = path.includes('?') ? '' : ifp;
|
|
return fetch(`${path}${ifp}${params}`, {
|
|
...configDefault,
|
|
...config,
|
|
});
|
|
}
|
|
|
|
return fetch(path, myInit);
|
|
}
|
|
|
|
// get
|
|
async function get(path, data, config) {
|
|
try {
|
|
const r = await request('GET', path, data, config);
|
|
const r_1 = await r.json();
|
|
return r_1;
|
|
} catch (err) {
|
|
return console.log('Request Failed', err);
|
|
}
|
|
}
|
|
|
|
// post
|
|
async function post(path, data, config) {
|
|
try {
|
|
const body = JSON.stringify(data);
|
|
const r = await request('POST', path, body, config);
|
|
const r_1 = await r.json();
|
|
return r_1;
|
|
} catch (err) {
|
|
return console.log('Request Failed', err);
|
|
}
|
|
}
|
|
|
|
// postForm
|
|
async function postForm(path, data, config) {
|
|
try {
|
|
const formData = new FormData();
|
|
Object.keys(data).forEach(key => {
|
|
formData.append(key, data[key]);
|
|
});
|
|
const r = await request('POST', path, formData, config);
|
|
const r_1 = await r.json();
|
|
return r_1;
|
|
} catch (err) {
|
|
return console.log('Request Failed', err);
|
|
}
|
|
}
|
|
function isEmpty(val) {
|
|
// return val === undefined || val === null || val === "";
|
|
return [Object, Array].includes((val || {}).constructor) && !Object.entries((val || {})).length;
|
|
}
|
|
function groupBy(array, callback) {
|
|
return array.reduce((groups, item) => {
|
|
const key = typeof callback === 'function' ? callback(item) : item[callback];
|
|
|
|
if (!groups[key]) {
|
|
groups[key] = [];
|
|
}
|
|
|
|
groups[key].push(item);
|
|
return groups;
|
|
}, {});
|
|
}
|