UNPKG

@opengis/fastify-table

Version:

core-plugins

80 lines (65 loc) 3.01 kB
import config from '../../../config.js'; import getTemplate from '../table/funcs/getTemplate.js'; import getMeta from '../pg/funcs/getMeta.js'; import pgClients from '../pg/pgClients.js'; import getInsertQuery from '../crud/funcs/utils/getInsertQuery.js'; const defaultTable = 'crm.extra_data'; function format(key, value, schema) { if (!key || !schema?.[key]) return value; if (schema?.[key]?.type && ['Number', 'Switcher'].includes(schema?.[key]?.type)) { return typeof value === 'string' ? JSON.parse(value) : value; } return value; } export default async function extraData({ table, form, id, data, uid, row = {}, }, pg = pgClients.client) { if (!id || !table) { return null; } const loadTemplate = await getTemplate('form', form); if (!loadTemplate?.extra) return null; const extraTable = config.extraData?.[table] || config.extraData?.[table.split('.').shift()] || config.extraData?.default || config.extraData || defaultTable; const { pk: mainPK, columns: mainColumns = [] } = await getMeta({ pg, table }); if (!mainPK) { return { error: `table pk not found: ${table}`, status: 404 }; } if (!pg.pk?.[extraTable]) { return { error: `extra table pk not found: ${extraTable}`, status: 404 }; } Object.assign(data || {}, { object_id: id }); const deleteRes = await pg.query(`delete from ${extraTable} where object_id=$1 and property_key = any($2::text[]) returning *`, [id, Object.keys(loadTemplate?.schema || {})]); if (!data) { const result = deleteRes?.rows?.reduce?.((acc, curr) => Object.assign(acc, { [curr.property_key]: format(curr.property_key, curr.value_text || curr.value_array, loadTemplate?.schema) }), {}) || {}; Object.assign(row, result); return result; } const rows = Object.keys(data || {}) .filter(key => Object.keys(loadTemplate?.schema || {}).includes(key)) .filter(key => !mainColumns.map(el => el.name).concat('id', 'token').includes(key)) .filter(key => (Array.isArray(data[key]) ? data[key].length : true)) .filter(key => !(loadTemplate?.schema?.[key]?.table && loadTemplate?.schema?.[key]?.parent_id)) .map(key => ({ object_id: id, property_key: key, property_entity: table, value_text: Array.isArray(data[key]) ? null : data[key], value_array: Array.isArray(data[key]) ? data[key] : null, })); const res = await Promise.all(rows.map(async (dataRow) => { const { insertQuery, args = [] } = await getInsertQuery({ pg, table: extraTable, data: dataRow, uid, }); if (!insertQuery || !args?.length) return {}; return pg.query(insertQuery, args).then(el => el.rows?.[0] || {}); })); Object.assign(row, { ...res.reduce((acc, curr) => Object.assign(acc, { [curr.property_key]: format(curr.property_key, curr.value_text || curr.value_array, loadTemplate?.schema) }), {}), id: res?.[0]?.object_id, }); return row; }