const apiHost = import.meta.env.PUBLIC_API_HOST;
const apiPort = import.meta.env.PUBLIC_API_PORT;
const appHost = import.meta.env.PUBLIC_APP_HOST;
const baseUrl = `http://${apiHost}:${apiPort}`;
const mobileUrl = `http://${appHost}:${apiPort}/mobile.html#/`
function buildUrl({ url, data = null }) {
const prefix = `${baseUrl}/api`;
let rurl = prefix + url;
if (data && Object.keys(data).length > 0) {
const { page, offset, where, order, pk } = data;
const params = ["pk=" + pk, "page=" + page, "offset=" + offset, "order=" + JSON.stringify(order), "where=" + JSON.stringify(where)];
rurl = prefix + url + "?" + params.join("&");
}
return rurl;
}
function buildOptions({ method, data }) {
const opts = {
method,
mode: "cors",
cache: "no-cache",
credentials: "same-origin",
headers: {
"Content-Type": "application/json",
},
referrerPolicy: "no-referrer",
}
if (data && method === "POST") {
opts.body = JSON.stringify(data);
}
return opts;
}
const doGet = async ({ url, data }) => {
try {
const response = await fetch(buildUrl({ url, data }), buildOptions({ method: "GET" }));
const result = await response.json();
return result;
} catch (error) {
console.error(error);
}
}
const doPost = async ({ url, data }) => {
try {
const response = await fetch(buildUrl({ url }), buildOptions({ method: "POST", data }));
const result = await response.json();
return result;
} catch (error) {
console.error(error);
}
}
export { doGet, doPost, baseUrl, mobileUrl }