@opengis/fastify-table
Version:
core-plugins
60 lines (59 loc) • 2.41 kB
JavaScript
import { readFileSync } from "node:fs";
import getMeta from "../../../plugins/pg/funcs/getMeta.js";
import pgClients from "../../../plugins/pg/pgClients.js";
import metaFormat from "../../../plugins/table/funcs/metaFormat/index.js";
import getTemplatePath from "../../../plugins/table/funcs/getTemplatePath.js";
import yml2json from "../../../plugins/yml/funcs/yml2json.js";
const infoList = [];
export default async function dataInfo({ pg = pgClients.client, params = {}, query = {}, }, reply) {
if (!infoList.length) {
const infoTemplateList = getTemplatePath("info")?.filter?.((el, idx, arr) => arr.findIndex((item) => item[1] === el[1]) === idx);
infoTemplateList?.forEach?.((el) => {
const info = yml2json(readFileSync(el[1], "utf-8"));
infoList.push(info);
});
}
const timeStart = Date.now();
const { id } = params;
const { table } = query;
const filteredList = table
? infoList.filter((el) => el.table === table)
: infoList;
if (!filteredList?.length) {
return reply.status(404).send("empty info templates list");
}
if (!id) {
return reply.status(400).send("not enough params: id");
}
const result = await Promise.all(filteredList
.filter((el) => el.table && pg.pk?.[el.table])
.map(async (el) => {
const { rowCount = 0, rows = [] } = await pg.query(`select ${pg.pk?.[el.table]} as id, ${el.columns?.map?.((item) => item?.replace?.(/'/g, "''")) || "*"} from ${el.table} where ${el.query || "true"} and ${pg.pk?.[el.table]}=$1`, [id]);
if (rowCount && rowCount > 0) {
const meta = await getMeta({ pg, table: el.table });
const columns = meta?.columns
?.filter((item) => el.columns?.includes?.(item.name))
?.map?.(({ name, title, dataTypeID }) => ({
name,
title,
type: pg.pgType?.[dataTypeID],
}));
return {
table: el.table,
columns,
rows,
cls: el.cls,
sufix: false,
};
}
return null;
}));
if (!result[0]?.table) {
return reply.status(404).send(`object not found: ${id}`);
}
await metaFormat(result[0], pg);
return {
time: Date.now() - timeStart,
...result[0],
};
}