datasquirel/client/fetch/index.ts
2026-01-01 09:52:53 +01:00

79 lines
2.2 KiB
TypeScript

import _ from "lodash";
import {
DSQLClientFetchHeader,
DSQLFetchApiOptions,
} from "../../package-shared/types";
/**
* # Fetch API
*/
export default async function fetchApi<
T extends { [k: string]: any } = { [k: string]: any },
R extends any = any
>(url: string, options?: DSQLFetchApiOptions<T>): Promise<R> {
let data;
let finalHeaders = {
"Content-Type": "application/json",
} as DSQLClientFetchHeader;
if (options?.csrfKey && options.csrfValue) {
finalHeaders[options.csrfKey] = options.csrfValue;
}
if (typeof options === "string") {
try {
let fetchData;
switch (options) {
case "post":
fetchData = await fetch(url, {
method: options,
headers: finalHeaders,
} 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") {
let fetchData;
let fetchOptions: RequestInit = {};
try {
if (options.method.match(/post|put|delete|patch/i)) {
if (options.body && typeof options.body == "object") {
fetchOptions.body = JSON.stringify(options.body);
}
}
fetchOptions.headers = _.merge(finalHeaders, options.headers || {});
fetchData = await fetch(url, fetchOptions);
data = fetchData.json();
} catch (error: any) {
console.log("FetchAPI error #2:", error.message);
console.log("fetchData =>", fetchData);
console.log("fetchOptions =>", fetchOptions);
data = null;
}
} else {
try {
let fetchData = await fetch(url);
data = await fetchData.json();
} catch (error: any) {
console.log("FetchAPI error #3:", error.message);
data = null;
}
}
return data;
}