import isArray from "lodash-es/isArray"; import isEmpty from "lodash-es/isEmpty"; import ky from "ky"; import type { HttpMethod, InvalidResponse, RawArgType, ValidResponse } from "../apiStructure/defs"; const apiPath = process.env.API_ROOT_PATH ?? process.env.VITE_API_ROOT_PATH ?? '/api'; export async function callClientAPI( method: HttpMethod, path: string | string[], args: RawArgType, paramArgs: Record | undefined ): Promise; export async function callClientAPI( method: HttpMethod, path: string | string[], args: RawArgType, paramArgs: Record | undefined, returnError: false ): Promise; export async function callClientAPI( method: HttpMethod, path: string | string[], args: RawArgType, paramArgs: Record | undefined, returnError: true ): Promise; export async function callClientAPI( method: HttpMethod, path: string | string[], args: RawArgType, paramArgs: Record | undefined, returnError = false ): Promise { if (isArray(path)) { path = path.join("/"); } if (args && isEmpty(args)) { args = undefined; } const result = (await (() => { if (method == "get") { return ky(apiPath, { searchParams: { ...paramArgs, ...(args as typeof paramArgs), path, }, method, headers: { "content-type": "application/json", }, timeout: 30000, retry: 0, }); } return ky(apiPath, { searchParams: { ...paramArgs, path, }, method, json: args, headers: { "content-type": "application/json", }, timeout: 30000, retry: 0, }); })().json()) as ErrorType | ResultType; if (!result.result) { if (returnError) { return result; } throw result.reason; } return result; }