UNPKG

@opengis/bi

Version:

BI data visualization module

69 lines (52 loc) 2.64 kB
import { config, pgClients, getMeta, setToken, getToken, } from '@opengis/fastify-table/utils.js'; export default async function datasetFormData({ pg = pgClients.client, params = {}, query = {}, user = {}, }) { if (!params?.id) { return { message: 'not enough params: id', status: 400 }; } if (!user?.uid) { return { message: 'access restricted', status: 403 }; } const { user_type: userType = 'regular' } = user; const tokenData = await getToken({ uid: user?.uid, token: params.id, mode: 'w', json: 1, }); if (!tokenData && !params?.object_id) { return { message: 'not enough params: object_id', status: 400 }; } const dataset = await pg.query(`select dataset_id as id, table_name as table, column_list as columns, filter_list as filters, sql_list as sql, style, form_setting, pk, access_level from bi.dataset where dataset_id=$1`, [tokenData?.dataset || params.id]).then(el => el.rows[0] || {}); if (!dataset?.id) { return { message: 'dataset not found', status: 404 }; } 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')`).then(el => el.rows[0]?.tlist || []); if (!dataset.table || !tlist.includes(dataset.table.replace(/"/g, '')) || (!pg.pk?.[dataset.table.replace(/"/g, '')] && !dataset.pk)) { return { message: `table not found: ${dataset.table}`, status: 404 }; } const { pk = dataset.pk, columns: dbColumns = [] } = await getMeta(dataset.table) || {}; const cols = dataset.columns?.filter((el) => el.name !== 'geom')?.map((el) => el.name || el)?.join(','); const where = [`"${pk}" = $1`, dataset.query].filter((el) => el); const geom = dbColumns.find((el) => el.name === 'geom' && pg.pgType[el.dataTypeID] === 'geometry') ? ',st_asgeojson(geom)::json as geom' : ''; const files = dbColumns.find((el) => el.name === 'files' && pg.pgType[el.dataTypeID] === 'text') ? ',files' : ''; const q = `select "${pk}" as id, ${cols || '*'} ${files} ${geom} from ${dataset.table} t where ${where.join(' and ') || 'true'} limit 1`; if (query.sql === '1' && (config.debug || userType.includes('admin'))) { return q; } const data = await pg.query(q, [tokenData?.id || params.object_id]).then(el => el.rows?.[0] || {}); data.token = setToken({ ids: [JSON.stringify({ id: data.id, table: dataset.table, form: `${dataset.id}.form`, dataset: dataset.id, })], uid: user?.uid, array: 1, })[0]; return data; }