First version without typescript errors
This commit is contained in:
@@ -1,4 +1,4 @@
|
||||
import DbClient from ".";
|
||||
import dbHandler from "../db-handler";
|
||||
import _ from "lodash";
|
||||
import type { APIResponseObject, ServerQueryParam } from "../../types";
|
||||
import sqlGenerator from "../../utils/sql-generator";
|
||||
@@ -12,6 +12,10 @@ type Params<
|
||||
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,
|
||||
@@ -39,30 +43,13 @@ export default async function DbDelete<
|
||||
}
|
||||
|
||||
sqlObj = sqlGenerator({
|
||||
tableName: table,
|
||||
tableName: quoteIdentifier(table),
|
||||
genObject: finalQuery,
|
||||
});
|
||||
|
||||
const whereClause = sqlObj.string.match(/WHERE .*/)?.[0];
|
||||
|
||||
if (whereClause) {
|
||||
let sql = `DELETE FROM ${table} ${whereClause}`;
|
||||
|
||||
sqlObj.string = sql;
|
||||
|
||||
const res = DbClient.run(sql, sqlObj.values);
|
||||
|
||||
return {
|
||||
success: Boolean(res.changes),
|
||||
postInsertReturn: {
|
||||
affectedRows: res.changes,
|
||||
insertId: Number(res.lastInsertRowid),
|
||||
},
|
||||
debug: {
|
||||
sqlObj,
|
||||
},
|
||||
};
|
||||
} else {
|
||||
if (!whereClause) {
|
||||
return {
|
||||
success: false,
|
||||
msg: `No WHERE clause`,
|
||||
@@ -71,6 +58,38 @@ export default async function DbDelete<
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
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,
|
||||
|
||||
Reference in New Issue
Block a user