86 lines
2.4 KiB
TypeScript
86 lines
2.4 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") {
|
|
try {
|
|
let fetchData;
|
|
|
|
if (options.body && typeof options.body === "object") {
|
|
let oldOptionsBody = _.cloneDeep(options.body);
|
|
options.body = JSON.stringify(oldOptionsBody);
|
|
}
|
|
|
|
if (options.headers) {
|
|
options.headers = _.merge(options.headers, finalHeaders);
|
|
|
|
const finalOptions: any = { ...options };
|
|
fetchData = await fetch(url, finalOptions);
|
|
} else {
|
|
const finalOptions = {
|
|
...options,
|
|
headers: finalHeaders,
|
|
} as RequestInit;
|
|
|
|
fetchData = await fetch(url, finalOptions);
|
|
}
|
|
|
|
data = fetchData.json();
|
|
} catch (error: any) {
|
|
console.log("FetchAPI error #2:", error.message);
|
|
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;
|
|
}
|