UNPKG

@opengis/fastify-table

Version:

core-plugins

91 lines (90 loc) 3.03 kB
import { dataDelete, getTemplate, getAccess, applyHook, getToken, config, pgClients, getOpt, } 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, })) || (await getOpt(params.id || params.table, user.uid)) || (await getOpt(params.table, user.uid)); const { table: del, id = params.id, query, actions: actionsToken, } = hookData || tokenData || (config.security?.disableToken || config.local || config.auth?.disable ? req.params : {}); if (actionsToken && !actionsToken?.includes("del")) { return reply.status(403).send({ error: "del is not allowed ", code: 403, }); } const { actions = [] } = (await getAccess({ table: del, id, user }, pg)) || {}; if (!tokenData && !config?.local && !config.security?.disableToken && !config.auth?.disable) { return reply.status(403).send({ error: "invalid token", code: 403, }); } if (!actions.includes("del") && !config?.local && !tokenData) { return reply.status(403).send({ error: "access restricted: actions", code: 403, }); } const loadTemplate = await getTemplate("table", del); const { table } = loadTemplate || hookData || tokenData || req.params || {}; if (!table) { return reply.status(404).send({ error: "table is required", code: 404, }); } if (!id) { return reply.status(404).send({ error: "id is required", code: 404, }); } const data = await dataDelete({ pg, table, id, uid: user?.uid, tokenData, referer, query, }).catch((err) => { if (err.message?.includes?.("foreign key") || err.message?.includes?.("unique")) { const constraint = err.message.match(/constraint "([^"]+)"/g); return reply.status(400).send({ error: `Видалення заборонено для збереження цілісності БД: ${constraint}`, code: 400, }); } if (config.trace) console.error(err.toString()); return { error: err.toString(), code: 400, }; }); return reply.status(200).send({ rowCount: data?.rowCount || 0, msg: !data?.rowCount ? data : null, }); }