UNPKG

@opengis/fastify-table

Version:

core-plugins

59 lines (45 loc) 2.07 kB
import { dataDelete, getTemplate, getAccess, applyHook, getToken, config, pgClients, } from '../../../../utils.js'; export default async function deleteCrud(req, reply) { const { pg = pgClients.client, user, params = {}, headers = {}, } = req || {}; const hookData = await applyHook('preDelete', { pg, table: params?.table, id: params?.id, user, }); if (hookData?.message && hookData?.status) { return reply.status(hookData.status).send(hookData.message); } const { referer } = headers; const tokenData = await getToken({ uid: user.uid, token: params.id || params.table, json: 1, }); const { table: del, id } = hookData || tokenData || (config.security?.disableToken || config.local || config.auth?.disable ? req.params : {}); const { actions = [] } = await getAccess({ table: del, id, user }, pg) || {}; if (!tokenData && !config?.local && !config.security?.disableToken && !config.auth?.disable) { return reply.status(400).send('invalid token'); } if (!actions.includes('del') && !config?.local && !tokenData) { return reply.status(403).send('access restricted: actions'); } const loadTemplate = await getTemplate('table', del); const { table } = loadTemplate || hookData || tokenData || req.params || {}; if (!table) { return reply.status(404).send('table is required'); } if (!id) { return reply.status(404).send('id is required'); } const data = await dataDelete({ pg, table, id, uid: user?.uid, tokenData, referer, }).catch(err => { if (err.message?.includes?.('foreign key' || 'unique')) { const constraint = err.message.match(/constraint "([^"]+)"/g); return reply.status(400).send(`Видалення заборонено для збереження цілісності БД: ${constraint}`); } if (config.trace) console.error(err.toString()); return err.toString(); }); return reply.status(200).send({ rowCount: data?.rowCount || 0, msg: !data?.rowCount ? data : null }); }