@replyke/express
Version:
Replyke: Build interactive apps with social features like comments, votes, feeds, user lists, notifications, and more.
75 lines (74 loc) • 3.19 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 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 { sequelize } = (0, config_1.getCoreConfig)();
try {
const { commentId } = req.params;
const loggedInUserId = req.userId;
const projectId = req.project.id;
if (!commentId) {
res.status(400).json({
error: "Missing comment ID",
code: "comment/missing-comment-id",
});
return;
}
// Delete the comment directly and ensure it's part of the project
const comment = (await models_1.Comment.findOne({
where: { id: commentId, projectId },
}));
// Check if the comment was found and deleted
if (!comment) {
res.status(404).json({
error: "Comment not found",
code: "comment/not-found",
});
return;
}
if (comment.userId !== loggedInUserId && !req.isMaster && !req.isService) {
res.status(403).json({
error: "You do not have permission to delete this comment.",
code: "comment/not-authorized",
});
return;
}
await sequelize.transaction(async (transaction) => {
await comment.destroy({ transaction });
await (0, updateUserReputation_1.default)(comment.userId, -reputation_scores_1.default.createComment, transaction);
// Recursive function to update `parentDeletedAt` for all replies
const updateReplies = async (parentCommentId, deletionDate) => {
// Find all direct replies to the current comment
const replies = (await models_1.Comment.findAll({
where: { parentId: parentCommentId, projectId },
transaction,
}));
// Update each reply's `parentDeletedAt` and call recursively for its replies
for (const reply of replies) {
await reply.update({ parentDeletedAt: deletionDate }, { transaction });
// Recursive call for nested replies
await updateReplies(reply.id, deletionDate);
}
};
// Set the deletion date
const deletionDate = new Date();
// Start the recursive update process for replies
await updateReplies(commentId, deletionDate);
});
res.sendStatus(204);
}
catch (err) {
console.error("Error deleting comment:", err);
res.status(500).json({
error: "Server error",
code: "comment/server-error",
details: err.message,
});
}
};