92 lines
2.6 KiB
TypeScript
92 lines
2.6 KiB
TypeScript
import { format } from "sql-formatter";
|
|
import {
|
|
APIResponseObject,
|
|
DSQL_TableSchemaType,
|
|
DsqlCrudParamWhereClause,
|
|
PostInsertReturn,
|
|
} from "../../../types";
|
|
import checkIfIsMaster from "../../../utils/check-if-is-master";
|
|
import connDbHandler from "../../../utils/db/conn-db-handler";
|
|
import { DbContextsArray } from "./runQuery";
|
|
|
|
type Param<T extends { [k: string]: any } = any, K extends string = string> = {
|
|
dbContext?: (typeof DbContextsArray)[number];
|
|
dbFullName?: string;
|
|
tableName: K;
|
|
tableSchema?: DSQL_TableSchemaType;
|
|
identifierColumnName?: keyof T;
|
|
identifierValue?: string | number;
|
|
forceLocal?: boolean;
|
|
whereClauseObject?: DsqlCrudParamWhereClause;
|
|
};
|
|
|
|
/**
|
|
* # Delete DB Entry Function
|
|
* @description
|
|
*/
|
|
export default async function deleteDbEntry<
|
|
T extends { [k: string]: any } = any,
|
|
K extends string = string
|
|
>({
|
|
dbContext,
|
|
dbFullName,
|
|
tableName,
|
|
identifierColumnName,
|
|
identifierValue,
|
|
forceLocal,
|
|
whereClauseObject,
|
|
}: Param<T, K>): Promise<APIResponseObject<PostInsertReturn>> {
|
|
try {
|
|
const isMaster = forceLocal
|
|
? true
|
|
: checkIfIsMaster({ dbContext, dbFullName });
|
|
|
|
/**
|
|
* Execution
|
|
*
|
|
* @description
|
|
*/
|
|
let query = `DELETE FROM ${
|
|
isMaster && !dbFullName ? "" : `\`${dbFullName}\`.`
|
|
}\`${tableName}\``;
|
|
|
|
let values: any[] = [];
|
|
|
|
if (whereClauseObject) {
|
|
query += ` ${whereClauseObject.clause}`;
|
|
values.push(...(whereClauseObject.params || []));
|
|
} else if (identifierColumnName && identifierValue) {
|
|
query += ` WHERE \`${identifierColumnName.toString()}\`=?`;
|
|
values = [identifierValue];
|
|
} else {
|
|
throw new Error(
|
|
`Delete operation has no specified rows! Can't delete everything in this table!`
|
|
);
|
|
}
|
|
|
|
const deletedEntry = (await connDbHandler({
|
|
query,
|
|
values,
|
|
})) as PostInsertReturn;
|
|
|
|
/**
|
|
* Return statement
|
|
*/
|
|
return {
|
|
success: Boolean(deletedEntry.affectedRows),
|
|
payload: deletedEntry,
|
|
queryObject: {
|
|
sql: format(query),
|
|
params: values,
|
|
},
|
|
};
|
|
} catch (error: any) {
|
|
const errorMsg = `Error Deleting Entry =>, ${error.message}`;
|
|
console.log(errorMsg);
|
|
return {
|
|
success: false,
|
|
msg: errorMsg,
|
|
};
|
|
}
|
|
}
|