@opengis/fastify-table
Version:
core-plugins
62 lines (58 loc) • 2 kB
JavaScript
import getMeta from "../../../pg/funcs/getMeta.js";
export default async function getInsertQuery({ pg, table, data, id, uid, }) {
if (!pg?.pk || !data) {
return null;
}
const { columns } = await getMeta({ pg, table });
if (!columns) {
return null;
}
const names = columns.map((col) => col.name);
const types = columns.reduce((acc, curr) => ({
...acc,
[curr.name]: pg.pgType?.[curr.dataTypeID],
}), {});
Object.assign(data, {
...(id && pg.pk?.[table] ? { [pg.pk?.[table]]: id } : {}),
...(table !== "admin.users" ? { uid } : {}),
editor_id: uid,
created_by: uid,
updated_by: uid,
});
const systemColumns = [
"cdate",
"editor_date",
"created_at",
"updated_at",
]
.filter((el) => names.includes(el))
.map((el) => [el, "now()"]);
const systemColumnNames = systemColumns.map((el) => el[0]);
const filterData = Object.keys(data)
.filter((el) => !systemColumnNames.includes(el) &&
(["boolean", "number"].includes(typeof data[el]) ? true : data[el]) &&
names.includes(el))
.map((el) => [el, data[el]]);
const insertQuery = `insert into ${table}
( ${filterData
?.map((key) => `"${key[0]}"`)
.concat(systemColumnNames)
.join(",")})
values (${filterData
?.map((key, i) => key[0] === "geom"
? `st_setsrid(st_geomfromgeojson($${i + 1}::json),4326)`
: `$${i + 1}`)
.concat(systemColumns.map((el) => el[1]))
.join(",")})
returning *`;
const args = [
...filterData.map((el) => typeof el[1] === "object" &&
(!Array.isArray(el[1]) ||
typeof el[1]?.[0] === "object" ||
types[el[0]] === "json")
? JSON.stringify(el[1])
: el[1]),
];
const keys = filterData.map((el) => el[0]);
return { insertQuery, args, keys, systemColumns };
}