datasquirel/package-shared/utils/data-fetching/crud.ts
Benjamin Toby e82bcd0824 Updates
2025-01-25 14:20:25 +01:00

96 lines
2.5 KiB
TypeScript

import get from "../../actions/get";
import post from "../../actions/post";
import sqlGenerator from "../../functions/dsql/sql/sql-generator";
import {
PostReturn,
ServerQueryParam,
ServerQueryQueryObject,
} from "../../types";
import numberfy from "../numberfy";
export const DsqlCrudActions = ["insert", "update", "delete", "get"] as const;
export type CrudQueryObject<T extends object = { [key: string]: any }> =
ServerQueryParam & {
query: ServerQueryQueryObject<T>;
};
export type CrudParam<T extends object = { [key: string]: any }> = {
action: (typeof DsqlCrudActions)[number];
table: string;
data?: T;
targetId?: string | number;
query?: CrudQueryObject<T>;
sanitize?: (data?: T) => T;
};
export default async function dsqlCrud<
T extends { [key: string]: any } = { [key: string]: any }
>({
action,
data,
table,
targetId,
query,
sanitize,
}: CrudParam<T>): Promise<
| (PostReturn & {
queryObject?: ReturnType<Awaited<typeof sqlGenerator>>;
})
| null
> {
const finalData = sanitize ? sanitize(data) : data;
const finalId = targetId;
let queryObject: ReturnType<Awaited<typeof sqlGenerator>> | undefined;
switch (action) {
case "get":
queryObject = sqlGenerator({
tableName: table,
genObject: query,
});
const GET_RES = await get({
query: queryObject?.string || "",
queryValues: queryObject?.values || [],
});
return { ...GET_RES, queryObject };
case "insert":
return await post({
query: {
action: "insert",
table,
data: finalData,
},
});
case "update":
delete data?.id;
return await post({
query: {
action: "update",
table,
identifierColumnName: "id",
identifierValue: String(finalId),
data: finalData,
},
});
case "delete":
return await post({
query: {
action: "delete",
table,
identifierColumnName: "id",
identifierValue: String(finalId),
},
});
default:
return null;
}
}