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): Promise { 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 { fetchOptions.method = options.method; 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 || {}); fetchOptions = _.merge(fetchOptions, options.fetchOptions); 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; }