UNPKG

@opengis/fastify-table

Version:

core-plugins

75 lines (59 loc) 2.01 kB
import { logger, dataInsert, pgClients } from '../../../../utils.js'; function checkValueType(val) { if (val && typeof val === 'object') { return 'property_json'; } if (val && typeof val === 'number' && (!/\D/.test(val.toString()) && val.toString().length < 10)) { return 'property_int'; } return 'property_text'; } export default async function postAppSettings({ pg = pgClients.client, body = {}, user = {}, params = {}, }, reply) { const { uid } = user; if ((!params.entity || params.entity === 'app') && !user?.user_type?.includes?.('admin')) { return reply.status(403).send('access restricted'); } if (!pg) { return reply.status(500).send('empty pg'); } if (!pg?.pk?.['admin.properties']) { return reply.status(404).send('table not found'); } const { key, val } = body; if ((!key || !val) && !Object.keys(body).length) { return reply.status(400).send('not enough body params'); } const keys = Object.keys(body); const entity = params.entity === 'user' ? user.uid : (params.entity || 'app'); const client = await pg.connect(); try { await client.query('begin;'); await client.query('delete from admin.properties where property_entity=$1 and property_key=any($2)', [entity, keys]); await Promise.all(keys.filter(el => body[el]).map(async (el) => { const columnType = checkValueType(body[el]); await dataInsert({ pg: client, table: 'admin.properties', data: { property_key: el, [columnType]: body[el], property_entity: entity, }, uid, }); })); await client.query('commit;'); return reply.status(200).send('ok'); } catch (err) { logger.file('properties/error', { error: err.toString(), stack: err.stack, body, user, entity, }); return reply.status(500).send(err.toString()); } finally { client.release(); } }