@opengis/bi
Version:
BI data visualization module
47 lines (34 loc) • 2.29 kB
JavaScript
import { handlebars } from "@opengis/fastify-table/utils.js";
import descriptionList from "./descriptionList.js";
// import metaFormat from "./metaFormat.js";
async function getDataById({ pg, table, id, time = [] }) {
const dataset = await pg.query(`select dataset_id as id, pk, query, table_name, column_list, setting
from bi.dataset where dataset_id=$1`, [table]).then((res) => res.rows[0] || {});
time.push(Date.now());
if (!dataset?.id) {
return { message: `dataset not found: ${table}`, status: 400 };
}
if (!dataset?.table_name) {
return { message: 'invalid dataset: empty params table', status: 400 };
}
const pk = dataset.pk || pg.pk?.[dataset.table_name];
const { rows = [] } = pk ? await pg.query(`select *, ${pk}, geom::json from ${dataset.table_name} where ${dataset.query || '1=1'} and ${pk}=$1`, [id]) || {} : {};
if (pk) rows.forEach((row) => Object.assign(row, { id: row?.[pk] }));
time.push(Date.now());
// sql columns
const sql = `select attname as name, pg_catalog.col_description(attrelid,attnum) as title, atttypid::regtype as type from pg_catalog.pg_attribute a
where attrelid='${dataset.table_name}'::regclass and attnum>0
and attname not in ('editor_id','editor_date','cdate','geom','id','uid','cdate')
and atttypid::regtype not in ('json','geometry')`;
// card or auto
const type = dataset.setting?.card_type || 'auto';
const list = dataset.setting?.card_list || [];
const { rows: all } = await pg.query(sql).then(el => el);
const columns = all.filter(el => type === 'list' ? list.includes(el.name) : true)
.map(el => `${el.title || el.name}| ${el.name}`).join('|')
const { body } = type === 'html' && dataset?.setting?.card ? await pg.query(`select body->>'body' as body from admin.doc_template where title=$1`, [dataset?.setting?.card]).then(el => el.rows[0] || {}) : {}
const html = body ? await handlebars.compile(body)(rows[0]) : await descriptionList(rows[0], { hash: { columns } });
time.push(Date.now());
return { id: rows?.[0]?.id, template: dataset?.setting?.card, rows, html, body };
}
export default getDataById