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"; export async function callClientAPI( method: HttpMethod, apiRoot: string, path: string | string[], args: RawArgType, paramArgs: Record | undefined ): Promise; export async function callClientAPI( method: HttpMethod, apiRoot: string, path: string | string[], args: RawArgType, paramArgs: Record | undefined, returnError: undefined ): Promise; export async function callClientAPI( method: HttpMethod, apiRoot: string, path: string | string[], args: RawArgType, paramArgs: Record | undefined, returnError: false ): Promise; export async function callClientAPI( method: HttpMethod, apiRoot: string, path: string | string[], args: RawArgType, paramArgs: Record | undefined, returnError: true ): Promise; export async function callClientAPI( method: HttpMethod, apiRoot: string, path: string | string[], args: RawArgType, paramArgs: Record | undefined, returnError?: boolean ): Promise { if (isArray(path)) { path = [apiRoot, ...path].join("/"); } else if (path.startsWith("/")) { path = `${apiRoot}${path}`; } else { path = `${apiRoot}/${path}`; } if (args && isEmpty(args)) { args = undefined; } const result = (await (() => { if (method == "get") { return ky(path, { searchParams: { ...paramArgs, ...(args as typeof paramArgs), }, method, headers: { "content-type": "application/json", }, timeout: 30000, retry: 0, }); } return ky(path, { searchParams: { ...paramArgs, }, 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; }