This commit is contained in:
2026-02-13 19:04:07 +01:00
parent 9505331165
commit 69d432b6af
42 changed files with 650 additions and 360 deletions
+20 -25
View File
@@ -1,4 +1,5 @@
import _ from "lodash";
import twuiSerializeQuery from "../serialize-query";
export const FetchAPIMethods = [
"POST",
@@ -17,6 +18,10 @@ type FetchApiOptions<T extends { [k: string]: any } = { [k: string]: any }> = {
method: (typeof FetchAPIMethods)[number];
body?: T | string;
headers?: FetchHeader;
query?: T;
csrfValue?: string;
csrfKey?: string;
fetchOptions?: RequestInit;
};
type FetchHeader = HeadersInit & {
@@ -35,32 +40,22 @@ export type FetchApiReturn = {
*/
export default async function fetchApi<
T extends { [k: string]: any } = { [k: string]: any },
R extends any = any
>(
url: string,
options?: FetchApiOptions<T>,
csrf?: boolean,
/**
* Key to use to grab local Storage csrf value.
*/
localStorageCSRFKey?: string,
/**
* Key with which to set the request header csrf
* value
*/
csrfHeaderKey?: string
): Promise<R> {
R extends any = any,
>(url: string, options?: FetchApiOptions<T>): Promise<R> {
let data;
const csrfKey = "x-dsql-csrf-key";
const csrfValue = localStorage.getItem(localStorageCSRFKey || csrfKey);
let finalHeaders = {
"Content-Type": "application/json",
} as FetchHeader;
if (csrf && csrfValue) {
finalHeaders[localStorageCSRFKey || csrfKey] = csrfValue;
if (options?.csrfKey && options.csrfValue) {
finalHeaders[options.csrfKey] = options.csrfValue;
}
let finalURL = url;
if (options?.query) {
finalURL += twuiSerializeQuery(options.query);
}
if (typeof options === "string") {
@@ -69,7 +64,7 @@ export default async function fetchApi<
switch (options) {
case "post":
fetchData = await fetch(url, {
fetchData = await fetch(finalURL, {
method: options,
headers: finalHeaders,
} as RequestInit);
@@ -77,7 +72,7 @@ export default async function fetchApi<
break;
default:
fetchData = await fetch(url);
fetchData = await fetch(finalURL);
data = fetchData.json();
break;
}
@@ -98,14 +93,14 @@ export default async function fetchApi<
options.headers = _.merge(options.headers, finalHeaders);
const finalOptions: any = { ...options };
fetchData = await fetch(url, finalOptions);
fetchData = await fetch(finalURL, finalOptions);
} else {
const finalOptions = {
...options,
headers: finalHeaders,
} as RequestInit;
fetchData = await fetch(url, finalOptions);
fetchData = await fetch(finalURL, finalOptions);
}
data = fetchData.json();
@@ -115,7 +110,7 @@ export default async function fetchApi<
}
} else {
try {
let fetchData = await fetch(url);
let fetchData = await fetch(finalURL);
data = await fetchData.json();
} catch (error: any) {
console.log("FetchAPI error #3:", error.message);