@opengis/fastify-table
Version:
core-plugins
88 lines (87 loc) • 2.77 kB
JavaScript
import getPG from "../../pg/funcs/getPG.js";
import getMeta from "../../pg/funcs/getMeta.js";
import getRedis from "../../redis/funcs/getRedis.js";
import pgClients from "../../pg/pgClients.js";
import config from "../../../../config.js";
import extraData from "../../extra/extraData.js";
import logChanges from "./utils/logChanges.js";
import logger from "../../logger/getLogger.js";
const rclient = getRedis();
export default async function dataDelete({ table: table1, tokenData, referer, id, pg: pg1, uid, query, }) {
const pg = pg1 || getPG({ name: "client" });
// pg client single transaction support
if (!pg?.pk && config.pg) {
pg.options = pgClients.client?.options;
pg.tlist = pgClients.client?.tlist;
pg.pgType = pgClients.client?.pgType;
pg.relkinds = pgClients.client?.relkinds;
pg.pk = pgClients.client?.pk;
}
const table = pg.pk?.[table1] ? table1 : table1.replace(/"/g, "");
if (!table)
return "table not exist";
const { pk } = await getMeta({ pg, table });
const delQuery = `delete from ${table} WHERE ${pk}::text = $1::text and ${query || "true"} returning *`;
// for transactions
const isClient = typeof pg.query === "function" && typeof pg.release === "function";
const client = isClient ? pg : await pg.connect();
if (isClient || !client.pk) {
client.options = pg.options;
client.tlist = pg.tlist;
client.pgType = pg.pgType;
client.relkinds = pg.relkinds;
client.pk = pg.pk;
}
try {
if (!isClient) {
await client.query("begin;");
}
const row = {};
await extraData({
table,
form: tokenData?.form,
id,
uid,
row,
}, client);
const res = await client
.query(delQuery, [id])
.then((el) => (el.rows?.[0] ? { rowCount: 1, ...el.rows[0] } : {}));
await logChanges({
pg: client,
table,
tokenData,
referer,
id,
uid,
type: "DELETE",
});
if (config.redis) {
rclient.incr(`pg:${table}:crud`);
}
if (!isClient) {
await client.query("commit;");
}
return { ...res, ...row };
}
catch (err) {
logger.file("crud/delete", {
error: err.toString(),
stack: err.stack,
table,
id,
referer,
uid,
form: tokenData?.form,
});
if (!isClient) {
await client.query("rollback;");
}
throw err;
}
finally {
if (!isClient) {
client?.release?.();
}
}
}