import get from "../../actions/get"; import post from "../../actions/post"; import sqlGenerator from "../../functions/dsql/sql/sql-generator"; import { DsqlCrudParam, PostReturn } from "../../types"; import connDbHandler, { ConnDBHandlerQueryObject } from "../db/conn-db-handler"; export default async function dsqlCrud< T extends { [key: string]: any } = { [key: string]: any } >({ action, data, table, targetValue, query, sanitize, debug, targetField, targetId, count, countOnly, }: DsqlCrudParam): Promise< | (PostReturn & { queryObject?: ReturnType>; count?: number; }) | null > { const finalData = sanitize ? sanitize(data) : data; let queryObject: ReturnType> | undefined; switch (action) { case "get": queryObject = sqlGenerator({ tableName: table, genObject: query, }); const DB_CONN = global.DSQL_READ_ONLY_DB_CONN || global.DSQL_DB_CONN; let connQueries: ConnDBHandlerQueryObject[] = [ { query: queryObject?.string, values: queryObject?.values || [], }, ]; const countQueryObject = count || countOnly ? sqlGenerator({ tableName: table, genObject: query, count: true, }) : undefined; if (count && countQueryObject) { connQueries.push({ query: countQueryObject.string, values: countQueryObject.values, }); } else if (countOnly && countQueryObject) { connQueries = [ { query: countQueryObject.string, values: countQueryObject.values, }, ]; } const res = await connDbHandler(DB_CONN, connQueries); const isSuccess = Array.isArray(res) && Array.isArray(res[0]); return { success: isSuccess, payload: isSuccess ? (countOnly ? null : res[0]) : null, error: isSuccess ? undefined : res?.error, queryObject, count: isSuccess ? res[1]?.[0]?.["COUNT(*)"] ? res[1][0]["COUNT(*)"] : res[0]?.[0]?.["COUNT(*)"] ? res[0][0]["COUNT(*)"] : undefined : undefined, }; case "insert": return await post({ query: { action: "insert", table, data: finalData, }, forceLocal: true, }); case "update": delete data?.id; return await post({ query: { action: "update", table, identifierColumnName: targetField || "id", identifierValue: String(targetValue || targetId), data: finalData, }, forceLocal: true, }); case "delete": return await post({ query: { action: "delete", table, identifierColumnName: targetField || "id", identifierValue: String(targetValue || targetId), }, forceLocal: true, }); default: return null; } }