new-personal-site/components/lib/utils/fetch/fetchApi.ts

114 lines
2.9 KiB
TypeScript
Raw Normal View History

2024-12-09 15:36:17 +00:00
import _ from "lodash";
type FetchApiOptions = {
method:
| "POST"
| "GET"
| "DELETE"
| "PUT"
| "PATCH"
| "post"
| "get"
| "delete"
| "put"
| "patch";
body?: object | string;
headers?: FetchHeader;
};
type FetchHeader = HeadersInit & {
2024-12-09 15:50:52 +00:00
[key: string]: string | null;
2024-12-09 15:36:17 +00:00
};
export type FetchApiReturn = {
success: boolean;
payload: any;
msg?: string;
[key: string]: any;
};
2025-01-05 06:25:38 +00:00
/**
* # Fetch API
*/
2024-12-09 15:36:17 +00:00
export default async function fetchApi(
url: string,
options?: FetchApiOptions,
2025-01-05 06:25:38 +00:00
csrf?: boolean,
/** Key to use to grab local Storage csrf value. */
localStorageCSRFKey?: string
2024-12-09 15:36:17 +00:00
): Promise<any> {
let data;
2025-01-05 06:25:38 +00:00
const csrfValue = localStorage.getItem(localStorageCSRFKey || "csrf");
let finalHeaders = {
"Content-Type": "application/json",
} as FetchHeader;
if (csrf && csrfValue) {
finalHeaders[`'${csrfValue.replace(/\"/g, "")}'`] = "true";
}
2024-12-09 15:36:17 +00:00
if (typeof options === "string") {
try {
let fetchData;
switch (options) {
case "post":
fetchData = await fetch(url, {
method: options,
2025-01-05 06:25:38 +00:00
headers: finalHeaders,
2024-12-09 15:36:17 +00:00
} 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;
if (options.body && typeof options.body === "object") {
let oldOptionsBody = _.cloneDeep(options.body);
options.body = JSON.stringify(oldOptionsBody);
}
if (options.headers) {
2025-01-05 06:25:38 +00:00
options.headers = _.merge(options.headers, finalHeaders);
2024-12-09 15:36:17 +00:00
const finalOptions: any = { ...options };
fetchData = await fetch(url, finalOptions);
} else {
2025-01-05 06:25:38 +00:00
const finalOptions = {
2024-12-09 15:36:17 +00:00
...options,
2025-01-05 06:25:38 +00:00
headers: finalHeaders,
} as RequestInit;
fetchData = await fetch(url, finalOptions);
2024-12-09 15:36:17 +00:00
}
data = fetchData.json();
} catch (error: any) {
console.log("FetchAPI error #2:", error.message);
data = null;
}
} else {
try {
let fetchData = await fetch(url);
2025-01-05 06:25:38 +00:00
data = await fetchData.json();
2024-12-09 15:36:17 +00:00
} catch (error: any) {
console.log("FetchAPI error #3:", error.message);
data = null;
}
}
return data;
}