@opengis/fastify-table
Version:
core-plugins
55 lines (54 loc) • 2.26 kB
JavaScript
import init from "./init.js";
import getPG from "./getPG.js";
const data = {};
export default async function getMeta(opt, nocache) {
const pg = opt?.pg || getPG({ name: "client" });
if (!pg)
return { error: "pg connection not established", status: 400 };
// reconnect if at start of process connection was unavailable
if (!pg.pk || nocache) {
await init(pg);
}
const table1 = opt?.table || opt;
const table = pg.pk?.[table1] ? table1 : table1?.replace?.(/"/g, "");
if (pg?.options?.database && data[pg.options.database]?.[table] && !nocache)
return data[pg.options.database][table];
if (!pg?.tlist?.includes(table) &&
!pg?.tlist?.includes(table?.replace?.(/"/g, ""))) {
return { error: `${table} - not found`, status: 400 };
}
const { fields = [] } = await pg.query(`select * from ${table} limit 0`);
const pks1 = await pg
.query(`SELECT json_object_agg(c.conrelid::regclass, a.attname) as pks1
FROM pg_constraint c
left join pg_attribute a on c.conrelid=a.attrelid and a.attnum = c.conkey[1]
WHERE c.contype='p'::"char" and c.conrelid::regclass = $1::regclass`, [table])
.then((el) => el.rows[0].pks1 || {});
const pk = table.startsWith("public.")
? pks1[table.replace("public.", "")]
: pks1[table];
const geomColumns = fields.filter((el) => pg.pgType?.[el.dataTypeID] === "geometry");
const geomAttr = geomColumns.find((el) => el.name === "geom_4326") || geomColumns[0];
const dbColumns = await pg
.query(`select json_object_agg(
attname,
json_build_object(
'title', pg_catalog.col_description(attrelid,attnum)
/*,'type', atttypid::regtype */
)
) from pg_catalog.pg_attribute a
where attrelid=$1::regclass and attnum>0`, [table])
.then((el) => el.rows?.[0]?.json_object_agg || {});
fields.forEach((el) => Object.assign(el, { ...(dbColumns[el.name] || {}) }));
const res = {
pk,
columns: fields,
geom: geomAttr?.name,
view: ["v", "m"].includes(pg.relkinds?.[table]),
};
if (!data[pg.options.database]) {
data[pg.options.database] = {};
}
data[pg.options.database][table] = res;
return res;
}