69 lines
1.8 KiB
JavaScript
69 lines
1.8 KiB
JavaScript
import dbHandler from "../db-handler";
|
|
import _ from "lodash";
|
|
import sqlGenerator from "../../utils/sql-generator";
|
|
function quoteIdentifier(identifier) {
|
|
return `\`${identifier.replace(/`/g, "``")}\``;
|
|
}
|
|
export default async function DbDelete({ table, query, targetId, config, }) {
|
|
let sqlObj = null;
|
|
try {
|
|
let finalQuery = query || {};
|
|
if (targetId) {
|
|
finalQuery = _.merge(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,
|
|
},
|
|
};
|
|
}
|
|
let sql = `DELETE FROM ${quoteIdentifier(table)} ${whereClause}`;
|
|
sql += ` RETURNING *`;
|
|
sqlObj.string = sql;
|
|
const res = await dbHandler({
|
|
query: sql,
|
|
values: sqlObj.values,
|
|
config,
|
|
});
|
|
if (!res.success) {
|
|
return {
|
|
success: false,
|
|
msg: "Database delete failed",
|
|
debug: {
|
|
sqlObj,
|
|
},
|
|
};
|
|
}
|
|
return {
|
|
..._.omit(res, ["payload"]),
|
|
success: Boolean(res.insert_return?.last_insert_id),
|
|
debug: {
|
|
sqlObj,
|
|
},
|
|
};
|
|
}
|
|
catch (error) {
|
|
return {
|
|
success: false,
|
|
error: error.message,
|
|
debug: {
|
|
sqlObj,
|
|
},
|
|
};
|
|
}
|
|
}
|