import dbHandler from "../db-handler"; import _ from "lodash"; import type { APIResponseObject, ServerQueryParam } from "../../types"; import sqlGenerator from "../../utils/sql-generator"; type Params< Schema extends { [k: string]: any } = { [k: string]: any }, Table extends string = string, > = { table: Table; query?: ServerQueryParam; targetId?: number | string; }; function quoteIdentifier(identifier: string): string { return `\`${identifier.replace(/`/g, "``")}\``; } export default async function DbDelete< Schema extends { [k: string]: any } = { [k: string]: any }, Table extends string = string, >({ table, query, targetId, }: Params): Promise { let sqlObj: ReturnType | null = null; try { let finalQuery = query || {}; if (targetId) { finalQuery = _.merge, ServerQueryParam>( finalQuery, { query: { id: { value: String(targetId), }, }, }, ); } sqlObj = sqlGenerator({ tableName: quoteIdentifier(table), genObject: finalQuery, }); const whereClause = sqlObj.string.match(/WHERE .*/)?.[0]; if (!whereClause) { return { success: false, msg: `No WHERE clause`, debug: { sqlObj, }, }; } const sql = `DELETE FROM ${quoteIdentifier(table)} ${whereClause}`; sqlObj.string = sql; const res = await dbHandler({ query: sql, values: sqlObj.values as any, }); if (!res.success) { return { success: false, msg: "Database delete failed", debug: { sqlObj, }, }; } const singleRes = res.single_res as any; return { success: Boolean(singleRes?.affectedRows), postInsertReturn: { affectedRows: Number(singleRes?.affectedRows), insertId: Number(singleRes?.insertId), }, debug: { sqlObj, }, }; } catch (error: any) { return { success: false, error: error.message, debug: { sqlObj, }, }; } }