@replyke/express
Version:
Replyke: Build interactive apps with social features like comments, votes, feeds, user lists, notifications, and more.
69 lines (68 loc) • 2.95 kB
JavaScript
;
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)();
if (!entityId) {
res.status(400).json({
error: "Invalid entityId.",
code: "entity/invalid-id",
});
return;
}
// First, fetch the entity using Sequelize's findOne method.
let 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 (entity.downvotes.includes(loggedInUserId)) {
res.status(409).json({
error: "User already downvoted entity.",
code: "entity/already-downvoted",
});
return;
}
await sequelize.transaction(async (transaction) => {
// Atomically increment upvotesCount and update upvotes array in the database
// await entity.increment("upvotesCount", { by: 1, transaction });
entity.set("downvotes", [...entity.downvotes, loggedInUserId]); // Add userId to downvotes
entity.set("upvotes", entity.upvotes.filter((upvote) => upvote !== loggedInUserId)); // Make sure userId is removed from upvotes in case they were there
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 or newly created entity.
res.status(200).json(populatedEntity.toJSON());
}
catch (err) {
console.error("Error downvoting an entity:", err);
res.status(500).json({
error: "Internal server error.",
code: "entity/server-error",
details: err.message,
});
}
};