datasquirel/package-shared/api-paths/index.ts
2025-12-26 10:33:46 +01:00

112 lines
3.3 KiB
TypeScript

import _ from "lodash";
import {
APIPathsCrudParams,
APIPathsParams,
APIResponseObject,
DsqlCrudQueryObject,
ServerQueryQueryObject,
} 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;
const finalSearchQuery = _.merge(
crudParams.query?.searchQuery,
crudParams.body?.searchQuery
);
if (finalSearchQuery) {
crudParams.query = {
...crudParams.query,
searchQuery: finalSearchQuery,
};
}
if (targetId) {
if (crudParams.query) {
if (crudParams.query.searchQuery) {
crudParams.query.searchQuery = _.merge<
DsqlCrudQueryObject<T>,
DsqlCrudQueryObject<T>
>(crudParams.query.searchQuery, {
query: {
id: {
value: String(targetId),
},
} as ServerQueryQueryObject<T, string>,
});
} else {
crudParams.query.searchQuery = {
query: {
id: {
value: String(targetId),
},
} as ServerQueryQueryObject<T, string>,
};
}
} else {
crudParams.query = {
searchQuery: {
query: {
id: {
value: String(targetId),
},
} as ServerQueryQueryObject<T, string>,
},
};
}
}
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,
};
}
}