56 lines
1.3 KiB
TypeScript
56 lines
1.3 KiB
TypeScript
import path from "path";
|
|
import {
|
|
APIResponseObject,
|
|
ClientCrudFetchParams,
|
|
PostInsertReturn,
|
|
} from "../../package-shared/types";
|
|
import serializeQuery from "../../package-shared/utils/serialize-query";
|
|
import fetchApi from "../fetch";
|
|
|
|
export default async function clientCrudFetch<
|
|
T extends { [k: string]: any } = { [k: string]: any },
|
|
P = string,
|
|
R extends { [k: string]: any } = { [k: string]: any }
|
|
>({
|
|
table,
|
|
basePath,
|
|
body,
|
|
query,
|
|
targetId,
|
|
method = "GET",
|
|
apiOrigin,
|
|
}: ClientCrudFetchParams<T, P>) {
|
|
try {
|
|
let pathname = basePath || ``;
|
|
|
|
pathname = path.join(pathname, String(table));
|
|
|
|
if (targetId) {
|
|
pathname = path.join(pathname, String(targetId));
|
|
}
|
|
|
|
if (query) {
|
|
pathname = `${pathname}${serializeQuery(query)}`;
|
|
}
|
|
|
|
pathname = apiOrigin
|
|
? `${apiOrigin}/${pathname}`.replace(/([^:]\/)\/+/g, "$1")
|
|
: pathname;
|
|
|
|
const res = await fetchApi<
|
|
any,
|
|
APIResponseObject<PostInsertReturn | R[]>
|
|
>(pathname, {
|
|
method,
|
|
body,
|
|
});
|
|
|
|
return res;
|
|
} catch (error: any) {
|
|
return {
|
|
success: false,
|
|
msg: `API ERROR => ${error.message}`,
|
|
};
|
|
}
|
|
}
|