Files
core_ng/server/clientAPI/generator.ts
T
2023-08-06 09:27:24 +00:00

81 lines
2.4 KiB
TypeScript

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<ResultType extends ValidResponse>(
method: HttpMethod,
path: string | string[],
args: RawArgType,
paramArgs: Record<string, string | number> | undefined
): Promise<ResultType>;
export async function callClientAPI<ResultType extends ValidResponse>(
method: HttpMethod,
path: string | string[],
args: RawArgType,
paramArgs: Record<string, string | number> | undefined,
returnError: false
): Promise<ResultType>;
export async function callClientAPI<ResultType extends ValidResponse, ErrorType extends InvalidResponse>(
method: HttpMethod,
path: string | string[],
args: RawArgType,
paramArgs: Record<string, string | number> | undefined,
returnError: true
): Promise<ResultType | ErrorType>;
export async function callClientAPI<ResultType extends ValidResponse, ErrorType extends InvalidResponse>(
method: HttpMethod,
path: string | string[],
args: RawArgType,
paramArgs: Record<string, string | number> | undefined,
returnError = false
): Promise<ResultType | ErrorType> {
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;
}