UNPKG

@opengis/fastify-table

Version:

core-plugins

53 lines (52 loc) 1.97 kB
import config from "../../../config.js"; import pgClients from "../pg/pgClients.js"; import getTemplate from "../table/funcs/getTemplate.js"; const defaultTable = "crm.extra_data"; function format(key, value, schema) { if (!key || !schema?.[key]) return undefined; // skip non-existing if (schema?.[key]?.type && ["datalist", "datatable", "number", "switcher"].includes(schema?.[key]?.type?.toLowerCase())) { return JSON.parse(value || null); } return value; } export default async function extraDataGet({ rows = [], table, form }, pg = pgClients.client) { const ids = rows .map((row) => row.id) .filter((el) => el); if (!ids?.length || !form || !table) { return null; } const loadTemplate = await getTemplate("form", form); if (!loadTemplate?.extra) return null; const extraDataTable = config.extraData?.[table] || config.extraData?.[table.split(".").shift()] || config.extraData?.default || config.extraData || defaultTable; if (!pg.pk?.[table]) { return { error: `table pk not found: ${table}`, status: 404 }; } if (!pg.pk?.[extraDataTable]) { return { error: `extra table pk not found: ${extraDataTable}`, status: 404, }; } const { rows: extraRows = [] } = await pg.query(`select * from ${extraDataTable} where object_id=any($1::text[])`, [ids]); if (rows?.length && extraRows?.length) { rows.forEach((row) => { Object.assign(row, { ...extraRows .filter((el) => el.object_id === row.id && (el.value_text || el.value_array)) .reduce((acc, curr) => { acc[curr.property_key] = format(curr.property_key, curr.value_text || curr.value_array, loadTemplate?.schema); return acc; }, {}), }); }); } return null; }