UNPKG

@opengis/fastify-table

Version:

core-plugins

82 lines (81 loc) 3.08 kB
import getSelect from "./getSelect.js"; import getFilterSQL from "./getFilterSQL/index.js"; import getTemplate from "./getTemplate.js"; import pgClients from "../../pg/pgClients.js"; import config from "../../../../config.js"; import getSelectVal from "./metaFormat/getSelectVal.js"; export default async function gisIRColumn({ pg = pgClients.client, layer, column, sql, query = {}, filter, state, search, custom, }) { const time = Date.now(); const sel = await getSelect(query.cls || column, pg); const body = await getTemplate("table", layer); const fData = await getFilterSQL({ pg, table: layer, filter, state, search, custom, }); const { tlist } = await pg .query(`select array_agg((select nspname from pg_namespace where oid=relnamespace)||'.'||relname) tlist from pg_class where relkind in ('r','v','m')`) .then((el) => el.rows?.[0] || {}); const tableName = body?.table || layer; if (!tlist.includes(tableName)) return { error: `table not found: ${tableName}`, status: 400 }; // eslint-disable-next-line max-len const { fields } = await pg.query(`select * from (${fData?.optimizedSQL || `select * from ${tableName}`})q limit 0`); const col = fields.find((el) => el.name === column); if (!col) return { status: 404, message: "not found" }; const colField = pg.pgType?.[col.dataTypeID]?.includes("[]") ? `unnest(${column})` : column; const q = `select ${colField} as id, count(*)::int from ( ${fData?.optimizedSQL || `select * from ${tableName} where ${body?.query || "true"}`} )t group by ${colField} order by count desc limit 15`; if (sql) return q; if (!body?.columns?.length) { const { rows } = await pg.query(q); if (sel?.arr?.length) { rows.forEach((el) => { const data = sel?.find((item) => item.id?.toString() === el.id?.toString()); Object.assign(el, data || {}); }); } return { count: rows?.reduce((acc, el) => acc + el.count, 0), sql: config.local ? q : undefined, rows, }; } const { rows } = await pg.query(q); const cls = query.cls || body?.columns?.find((el) => el.name === column)?.data; // || col.data // || col.option; const select = await getSelectVal({ pg, name: cls, values: rows.map((el) => el.id), ar: 1, }); rows.forEach((el) => { if (Array.isArray(select)) { Object.assign(el, select.find((item) => item.id?.toString() === el.id?.toString()) || {}); } else if (typeof select?.[el.id] === "string") { Object.assign(el, { text: select?.[el.id] }); } else { Object.assign(el, select?.[el.id] || {}); } }); return { time: Date.now() - time, count: rows.reduce((acc, el) => acc + el.count, 0), sql: config.local ? q : undefined, rows, }; }