Files
modstagram-back/utils/commentEngagement.js
payacom 3f416a7a60 full
2026-08-31 20:45:41 +03:30

35 lines
948 B
JavaScript

const CommentLikeModel = require('../models/CommentLikeModel')
async function attachCommentLikeFields(comments, viewerId) {
if (!comments?.length) return comments
const ids = comments.map((c) => c._id)
const [likeAgg, userLikes] = await Promise.all([
CommentLikeModel.aggregate([
{ $match: { commentId: { $in: ids } } },
{ $group: { _id: '$commentId', count: { $sum: 1 } } },
]),
viewerId
? CommentLikeModel.find({
userId: viewerId,
commentId: { $in: ids },
})
.select('commentId')
.lean()
: [],
])
const countMap = Object.fromEntries(
likeAgg.map((row) => [String(row._id), row.count])
)
const likedSet = new Set(userLikes.map((l) => String(l.commentId)))
return comments.map((c) => ({
...c,
likesCount: countMap[String(c._id)] || 0,
is_liked: likedSet.has(String(c._id)),
}))
}
module.exports = { attachCommentLikeFields }