UNPKG

@replyke/express

Version:

Replyke: Build interactive apps with social features like comments, votes, feeds, user lists, notifications, and more.

76 lines (75 loc) 2.85 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); const models_1 = require("../../../models"); const updateUserReputation_1 = __importDefault(require("../../../helpers/updateUserReputation")); const reputation_scores_1 = __importDefault(require("../../../constants/reputation-scores")); const config_1 = require("../../../config"); exports.default = async (req, res) => { const { entityId } = req.params; const loggedInUserId = req.userId; const projectId = req.project.id; const { sequelize } = (0, config_1.getCoreConfig)(); if (!entityId) { res.status(400).json({ error: "Invalid entityId.", code: "entity/invalid-id", }); return; } try { // Fetch the entity to get the author (userId) const entity = (await models_1.Entity.findOne({ where: { projectId, id: entityId }, })); if (!entity) { res.status(404).json({ error: "Entity not found.", code: "entity/not-found", }); return; } // Determine if current user is admin or the author const isAuthor = entity.userId === loggedInUserId; // If the user is not admin and not author, they cannot delete if (!isAuthor && !req.isMaster && !req.isService) { res.status(403).json({ error: "Not authorized to delete this entity.", code: "entity/not-authorized", }); return; } const deletedCount = await sequelize.transaction(async (t) => { // a) perform the delete const count = await models_1.Entity.destroy({ where: { projectId, id: entityId }, transaction: t, }); // b) only if something was deleted do we remove reputation if (count > 0 && entity.userId) { await (0, updateUserReputation_1.default)(entity.userId, -reputation_scores_1.default.createEntity, t); } return count; }); // 3. Now check the result if (deletedCount === 0) { // no rows were deleted → nothing to undo res.status(404).json({ error: "Entity not found or already deleted.", code: "entity/delete-failed", }); return; } res.sendStatus(204); } catch (err) { console.error("Failed to delete the entity:", err); res.status(500).json({ error: "Failed to delete the entity.", code: "entity/server-error", details: err.message, }); } };