UNPKG

@opengis/bi

Version:

BI data visualization module

91 lines (75 loc) 2.94 kB
import { dataUpdate, pgClients } from '@opengis/fastify-table/utils.js'; const columnTypeMatch = { text: 'text', select: 'text', date: 'date', 'yes/no': 'boolean', badge: 'text', number: 'numeric', tags: 'text[]', geom: 'geom', }; /** * Редагування структури набору даних * * @method PUT * @summary Редагування структури набору даних * @priority 4 * @alias editDataset * @type api * @tag bi * @param {Object} query.id Видалення ID * @errors 400,500 * @returns {Number} status Номер помилки * @returns {String} error Опис помилки * @returns {Object} rows Масив з колонками таблиці */ export default async function editDataset(req) { const { pg = pgClients.client, query = {}, body = {}, user = {}, } = req; if (!user?.uid) { return { message: 'access restricted', status: 403 }; } if (!query?.id) { return { message: 'not enough params: id', status: 404 }; } if (!body.column_list?.length) { return { message: 'not enough params: columns', status: 400 }; } const dataset = await pg.query('select dataset_id as id, table_name as table, column_list as columns from bi.dataset where dataset_id=$1', [query.id]) .then(el => el.rows[0] || {}); if (!dataset?.id) { return { message: 'dataset not found', status: 404 }; } if (!dataset.table || !pg.pk?.[dataset.table]) { return { message: `table not found: ${dataset.table}`, status: 404 }; } if (!dataset.table.startsWith('data_user.')) { return { message: 'access restricted: source', status: 403 }; } const { fields = [] } = await pg.query(`select * from ${dataset.table} limit 0`); const columnList = fields.map((col) => col.name); const columns = (dataset.columns || []) .concat(body.column_list.filter((col) => !col.name || !columnList.includes(col.name))) .map((col, idx) => ({ ...col, name: col.name && columnList.includes(col.name) ? col.name : `col_${idx}`, disabled: col.name && !body.column_list.find((item) => item.name === col.name), })); await dataUpdate({ pg, table: 'bi.dataset', data: { column_list: columns }, id: dataset.id, uid: user.uid, }); const sqlList = columns .filter((col) => col.name.startsWith('col_') || (col.title && dataset.columns?.find?.((item) => item.name === col.name)?.title !== col.title)) .map((col) => `alter table ${dataset.table} add column if not exists ${col.name} ${columnTypeMatch[col.type] || 'text'}; comment on column ${dataset.table}."${col.name}" is '${(col.title || col.name).replace(/'/g, "''")}'`); if (sqlList.length) { await pg.query(sqlList.join(';')); } return { message: { id: dataset?.id, table: dataset.table, columns }, status: 200 }; }