75 lines
2.1 KiB
TypeScript
75 lines
2.1 KiB
TypeScript
import _ from "lodash";
|
|
import {
|
|
APIPathsCrudParams,
|
|
APIPathsParams,
|
|
APIResponseObject,
|
|
} from "../types";
|
|
import getResult from "./functions/get-result";
|
|
import { grabPathData } from "./utils/grab-path-data";
|
|
import checks from "./utils/checks";
|
|
import postResult from "./functions/post-result";
|
|
import putResult from "./functions/put-result";
|
|
import deleteResult from "./functions/delete-result";
|
|
|
|
export default async function apiCrudHandler<
|
|
T extends { [k: string]: any } = { [k: string]: any }
|
|
>(params: APIPathsParams<T>): Promise<APIResponseObject> {
|
|
try {
|
|
const { auth, method } = params;
|
|
|
|
const isAuthorized = await auth?.();
|
|
|
|
const { table, targetId, url, query } = grabPathData<T>(params);
|
|
|
|
const crudParams: APIPathsCrudParams<T> = {
|
|
...params,
|
|
isAuthorized,
|
|
table,
|
|
targetId,
|
|
};
|
|
|
|
const checkedObj = await checks<T>({
|
|
...crudParams,
|
|
query: _.merge(params.query || {}, query),
|
|
});
|
|
|
|
crudParams.query = checkedObj.query;
|
|
crudParams.body = checkedObj.body;
|
|
crudParams.allowedTable = checkedObj.allowedTable;
|
|
crudParams.url = url;
|
|
|
|
if (targetId) {
|
|
if (crudParams.query) {
|
|
if (crudParams.query.crudParams) {
|
|
crudParams.query.crudParams.targetId = targetId;
|
|
} else {
|
|
crudParams.query.crudParams = {
|
|
targetId,
|
|
};
|
|
}
|
|
}
|
|
}
|
|
|
|
switch (method) {
|
|
case "GET":
|
|
return await getResult(crudParams);
|
|
case "POST":
|
|
return await postResult(crudParams);
|
|
case "PUT":
|
|
return await putResult(crudParams);
|
|
case "DELETE":
|
|
return await deleteResult(crudParams);
|
|
}
|
|
|
|
return {
|
|
success: false,
|
|
msg: `Unhandled`,
|
|
};
|
|
} catch (error: any) {
|
|
return {
|
|
success: false,
|
|
msg: error.message,
|
|
};
|
|
}
|
|
}
|