This commit is contained in:
Benjamin Toby
2025-01-05 07:25:38 +01:00
parent 998158369a
commit 5587024789
30 changed files with 4756 additions and 75 deletions
+24 -16
View File
@@ -27,26 +27,37 @@ export type FetchApiReturn = {
[key: string]: any;
};
/**
* # Fetch API
*/
export default async function fetchApi(
url: string,
options?: FetchApiOptions,
csrf?: boolean
csrf?: boolean,
/** Key to use to grab local Storage csrf value. */
localStorageCSRFKey?: string
): Promise<any> {
let data;
const csrfValue = localStorage.getItem(localStorageCSRFKey || "csrf");
let finalHeaders = {
"Content-Type": "application/json",
} as FetchHeader;
if (csrf && csrfValue) {
finalHeaders[`'${csrfValue.replace(/\"/g, "")}'`] = "true";
}
if (typeof options === "string") {
try {
let fetchData;
const csrfValue = localStorage.getItem("csrf");
switch (options) {
case "post":
fetchData = await fetch(url, {
method: options,
headers: {
"Content-Type": "application/json",
"x-csrf-auth": csrf ? csrfValue : "",
} as FetchHeader,
headers: finalHeaders,
} as RequestInit);
data = fetchData.json();
break;
@@ -64,26 +75,23 @@ export default async function fetchApi(
try {
let fetchData;
const csrfValue = localStorage.getItem("csrf");
if (options.body && typeof options.body === "object") {
let oldOptionsBody = _.cloneDeep(options.body);
options.body = JSON.stringify(oldOptionsBody);
}
if (options.headers) {
options.headers["x-csrf-auth"] = csrf ? csrfValue : "";
options.headers = _.merge(options.headers, finalHeaders);
const finalOptions: any = { ...options };
fetchData = await fetch(url, finalOptions);
} else {
fetchData = await fetch(url, {
const finalOptions = {
...options,
headers: {
"Content-Type": "application/json",
"x-csrf-auth": csrf ? csrfValue : "",
} as FetchHeader,
} as RequestInit);
headers: finalHeaders,
} as RequestInit;
fetchData = await fetch(url, finalOptions);
}
data = fetchData.json();
@@ -94,7 +102,7 @@ export default async function fetchApi(
} else {
try {
let fetchData = await fetch(url);
data = fetchData.json();
data = await fetchData.json();
} catch (error: any) {
console.log("FetchAPI error #3:", error.message);
data = null;