UNPKG

@replyke/express

Version:

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

71 lines (70 loc) 3.03 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 sequelize_query_params_1 = require("../../../constants/sequelize-query-params"); 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) => { try { const { entityId } = req.params; const loggedInUserId = req.userId; const projectId = req.project.id; const { sequelize } = (0, config_1.getCoreConfig)(); // Validate the presence of entityId and userId. if (!entityId) { res.status(400).json({ error: "Invalid entity ID.", code: "entity/invalid-id", }); return; } // Fetch the entity with a row lock for safe update (if transaction is used). 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; } // If the entity does not exist or the user hasn't liked it. if (!entity.upvotes.includes(loggedInUserId)) { res.status(409).json({ error: "Can't remove upvote, as user didn't upvote entity or entity not found.", code: "entity/not-upvoted", }); return; } await sequelize.transaction(async (transaction) => { // Update the entity by removing the user's ID from upvotes and decrementing upvotesCount. entity.set("upvotes", entity.upvotes.filter((upvote) => upvote !== loggedInUserId)); // entity.set("upvotesCount", Math.max(entity.upvotesCount - 1, 0)); // Save the updated entity within the transaction. await entity.save({ transaction }); if (entity.userId) { await (0, updateUserReputation_1.default)(entity.userId, -reputation_scores_1.default.upvote, transaction); } }); // Fetch the entity again but populated now const populatedEntity = (await models_1.Entity.findOne({ where: { id: entity.id }, ...sequelize_query_params_1.entityParams, })); // Return the updated entity. res.status(200).json(populatedEntity.toJSON()); } catch (err) { console.error("Error removing upvote from entity:", err); res.status(500).json({ error: "Internal server error.", code: "entity/server-error", details: err.message, }); } };