datasquirel/client/fetch/index.js

96 lines
3.0 KiB
JavaScript
Raw Normal View History

2024-11-08 17:28:55 +00:00
// @ts-check
const _ = require("lodash");
2024-11-08 15:41:22 +00:00
/** @type {import("../../package-shared/types").FetchApiFn} */
2024-11-08 17:28:55 +00:00
async function clientFetch(url, options, contentType) {
2024-11-08 15:41:22 +00:00
let data;
2024-11-08 17:28:55 +00:00
let finalUrl = url;
2024-11-08 15:41:22 +00:00
if (typeof options === "string") {
try {
let fetchData;
switch (options) {
case "post":
2024-11-08 17:28:55 +00:00
fetchData = await fetch(finalUrl, {
2024-11-08 15:41:22 +00:00
method: options,
headers: {
"Content-Type": "application/json",
},
});
2024-11-08 17:28:55 +00:00
data = await fetchData.json();
2024-11-08 15:41:22 +00:00
break;
default:
2024-11-08 17:28:55 +00:00
fetchData = await fetch(finalUrl);
data = await fetchData.json();
2024-11-08 15:41:22 +00:00
break;
}
} catch (/** @type {any} */ error) {
console.log("FetchAPI error #1:", error.message);
data = null;
}
} else if (typeof options === "object") {
try {
let fetchData;
2024-11-08 17:28:55 +00:00
if (options.query) {
let pathSuffix = "";
pathSuffix += "?";
const queryString = Object.keys(options.query)
?.map((queryKey) => {
if (!options.query?.[queryKey]) return undefined;
if (typeof options.query[queryKey] == "object") {
return `${queryKey}=${JSON.stringify(
options.query[queryKey]
)}`;
}
return `${queryKey}=${options.query[queryKey]}`;
})
.filter((prt) => prt)
.join("&");
pathSuffix += queryString;
finalUrl += pathSuffix;
delete options.query;
}
2024-11-08 15:41:22 +00:00
if (options.body && typeof options.body === "object") {
let oldOptionsBody = _.cloneDeep(options.body);
options.body = JSON.stringify(oldOptionsBody);
}
if (options.headers) {
2024-11-08 17:28:55 +00:00
/** @type {any} */
2024-11-08 15:41:22 +00:00
const finalOptions = { ...options };
2024-11-08 17:28:55 +00:00
fetchData = await fetch(finalUrl, finalOptions);
2024-11-08 15:41:22 +00:00
} else {
2024-11-08 17:28:55 +00:00
fetchData = await fetch(finalUrl, {
2024-11-08 15:41:22 +00:00
...options,
headers: {
"Content-Type": "application/json",
},
});
}
2024-11-08 17:28:55 +00:00
data = await fetchData.json();
2024-11-08 15:41:22 +00:00
} catch (/** @type {any} */ error) {
console.log("FetchAPI error #2:", error.message);
data = null;
}
} else {
try {
2024-11-08 17:28:55 +00:00
let fetchData = await fetch(finalUrl);
data = await fetchData.json();
2024-11-08 15:41:22 +00:00
} catch (/** @type {any} */ error) {
console.log("FetchAPI error #3:", error.message);
data = null;
}
}
return data;
}
module.exports = clientFetch;
exports.fetchApi = clientFetch;