new-personal-site/components/lib/utils/fetch/fetchApi.ts
2024-12-09 16:36:17 +01:00

107 lines
3.0 KiB
TypeScript
Executable File

import { AuthCsrfHeaderName } from "@/server-client-shared/types/admin/auth";
import _ from "lodash";
type FetchApiOptions = {
method:
| "POST"
| "GET"
| "DELETE"
| "PUT"
| "PATCH"
| "post"
| "get"
| "delete"
| "put"
| "patch";
body?: object | string;
headers?: FetchHeader;
};
type FetchHeader = HeadersInit & {
[key in AuthCsrfHeaderName]?: string | null;
};
export type FetchApiReturn = {
success: boolean;
payload: any;
msg?: string;
[key: string]: any;
};
export default async function fetchApi(
url: string,
options?: FetchApiOptions,
csrf?: boolean
): Promise<any> {
let data;
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,
} as RequestInit);
data = fetchData.json();
break;
default:
fetchData = await fetch(url);
data = fetchData.json();
break;
}
} catch (error: any) {
console.log("FetchAPI error #1:", error.message);
data = null;
}
} else if (typeof options === "object") {
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 : "";
const finalOptions: any = { ...options };
fetchData = await fetch(url, finalOptions);
} else {
fetchData = await fetch(url, {
...options,
headers: {
"Content-Type": "application/json",
"x-csrf-auth": csrf ? csrfValue : "",
} as FetchHeader,
} as RequestInit);
}
data = fetchData.json();
} catch (error: any) {
console.log("FetchAPI error #2:", error.message);
data = null;
}
} else {
try {
let fetchData = await fetch(url);
data = fetchData.json();
} catch (error: any) {
console.log("FetchAPI error #3:", error.message);
data = null;
}
}
return data;
}