35 lines
948 B
JavaScript
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 }
|