UNPKG

@opengis/bi

Version:

BI data visualization module

104 lines (90 loc) 4.07 kB
import path from 'node:path'; import { config, logger, pgClients, getTemplate, getTemplatePath, dataInsert, dataUpdate, } from '@opengis/fastify-table/utils.js'; export default async function dashboardImport({ pg = pgClients.client, query = {}, user = {} }, reply) { const time = Date.now(); if (!query?.dashboard) { return reply.status(400).send('not enough query params: dashboard'); } const list = getTemplatePath('dashboard').filter(el => el[0] === query.dashboard); if (!list?.length) { return reply.status(404).send(`dashboard not found`); } const client = await pg.connect(); Object.assign(client, { options: pg.options, pk: pg.pk, pgType: pg.pgType, tlist: pg.tlist, }); const ids = []; try { await client.query('BEGIN'); const rows = await Promise.all(list.map(async ([filename]) => { const obj = await getTemplate('dashboard', filename); const index = obj?.find((el) => el[0] === 'index.yml')?.[1]; const { db = pg.options?.database, description, filters, panels, table_name, title, tags, style, grid } = index || {}; const dashboardId = await dataInsert({ pg, table: 'bi.dashboard', data: { db, name: filename, description, filters, panels, table_name, title, words: tags?.join(','), style, grid, source: 'file', }, uid: user?.uid, }).then(el => el.rows?.[0]?.dashboard_id); ids.push(dashboardId); const widgetList = panels?.reduce((acc, curr) => { curr.widgets?.forEach(item => acc.push(item)); if (curr.widget) acc.push(curr.widget); return acc; }, []).filter(el => el) || []; const widgets = widgetList.length ? await Promise.all(obj.filter(el => widgetList.includes(path.parse(el[0]).name)).map(async ([widget, widgetData]) => { const { ext, name } = path.parse(widget); const data = ext === '.yml' ? widgetData : { type: 'text', data: { text: widgetData } }; Object.assign(data, { name, x: widgetData?.data?.x, table_name: widgetData?.data?.table, dashboard_id: dashboardId }); const res = await dataInsert({ pg: client, table: 'bi.widget', data, uid: user?.uid, }).then(el => el.rows?.[0] || {}); return res; })) : []; const test = await dataUpdate({ pg: client, table: 'bi.dashboard', id: dashboardId, data: { widgets, }, uid: user?.uid, }); return { dashboardId, name: filename, widgets }; })); await client.query('COMMIT'); return { time: Date.now() - time, rows }; } catch (err) { await client.query('ROLLBACK'); if (ids.length) { const { rowCount = 0 } = await pg.query('delete from bi.dashboard where dashboard_id = any($1)', [ids]); console.log('ROLLBACK delete', rowCount, 'dashboard'); // const { rowCount: rowCount1 = 0 } = await pg.query('delete from bi.widget where dashboard_id = any($1)', [ids]); // console.log('delete', rowCount1, 'widget'); } logger.file('bi/dashboardImport/error', { error: err.toString(), stack: err.stack, ids }); return reply.status(500).send(config.debug ? err.toString() : 'import error'); } }