merge: request.js;

main
Lei OT 4 months ago
parent 22697c365b
commit 7e990057d4

@ -1,5 +1,3 @@
// import { BUILD_VERSION } from '@/config'
const BUILD_VERSION = ''
// Ref: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
@ -21,6 +19,20 @@ function getRequestHeader() {
}, {});
}
const initParams = [];
export function appendRequestParams(n, v) {
initParams.push({
name: n,
value: v
})
}
function getRequestInitParams() {
return initParams.reduce((acc, item) => {
acc[item.name] = item.value;
return acc;
}, {});
}
function checkStatus(response) {
if (response.status >= 200 && response.status < 300) {
return response
@ -52,16 +64,20 @@ export function fetchText(url) {
}
}).then(checkStatus)
.then(response => response.text())
.then(checkBizCode)
.catch(error => {
throw error
})
}
export function fetchJSON(url, data) {
const params = data ? new URLSearchParams(data).toString() : '';
const ifp = url.includes('?') ? (data ? '&' : '') : '?';
const headerObj = getRequestHeader()
return fetch(`${url}${ifp}${params}`, {
export function fetchJSON(url, data = {}) {
const initParams = getRequestInitParams();
const params4get = Object.assign({}, initParams, data);
const params = params4get ? new URLSearchParams(params4get).toString() : '';
const ifp = url.includes('?') ? '&' : '?';
const headerObj = getRequestHeader();
const fUrl = params !== '' ? `${url}${ifp}${params}` : url;
return fetch(fUrl, {
method: 'GET',
headers: {
'X-Web-Version': BUILD_VERSION,
@ -76,6 +92,12 @@ export function fetchJSON(url, data) {
}
export function postForm(url, data) {
const initParams = getRequestInitParams();
Object.keys(initParams).forEach(key => {
if (! data.has(key)) {
data.append(key, initParams[key]);
}
});
const headerObj = getRequestHeader()
return fetch(url, {
method: 'POST',
@ -93,8 +115,14 @@ export function postForm(url, data) {
}
export function postJSON(url, obj) {
const initParams = getRequestInitParams();
const params4get = Object.assign({}, initParams);
const params = new URLSearchParams(params4get).toString();
const ifp = url.includes('?') ? '&' : '?';
const fUrl = params !== '' ? `${url}${ifp}${params}` : url;
const headerObj = getRequestHeader()
return fetch(url, {
return fetch(fUrl, {
method: 'POST',
body: JSON.stringify(obj),
headers: {
@ -127,3 +155,19 @@ export function postStream(url, obj) {
throw error
})
}
export function delJSON(url, obj) {
const host = /^https?:\/\//i.test(url) ? '': HT_HOST;
return fetch(`${host}${url}`, {
method: 'DELETE',
body: JSON.stringify(obj),
headers: {
'Content-type': 'application/json; charset=UTF-8'
}
}).then(checkStatus)
.then(response => response.json())
.then(checkBizCode)
.catch(error => {
throw error;
});
}

Loading…
Cancel
Save