95 lines
2.8 KiB
TypeScript
95 lines
2.8 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.js";
|
|
|
|
export async function callClientAPI<ResultType extends ValidResponse>(
|
|
method: HttpMethod,
|
|
apiRoot: string,
|
|
path: string | string[],
|
|
args: RawArgType,
|
|
paramArgs: Record<string, string | number> | undefined
|
|
): Promise<ResultType>;
|
|
export async function callClientAPI<ResultType extends ValidResponse>(
|
|
method: HttpMethod,
|
|
apiRoot: string,
|
|
path: string | string[],
|
|
args: RawArgType,
|
|
paramArgs: Record<string, string | number> | undefined,
|
|
returnError: undefined
|
|
): Promise<ResultType>;
|
|
export async function callClientAPI<ResultType extends ValidResponse>(
|
|
method: HttpMethod,
|
|
apiRoot: string,
|
|
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,
|
|
apiRoot: string,
|
|
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,
|
|
apiRoot: string,
|
|
path: string | string[],
|
|
args: RawArgType,
|
|
paramArgs: Record<string, string | number> | undefined,
|
|
returnError?: boolean
|
|
): Promise<ResultType | ErrorType> {
|
|
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;
|
|
} |