nakama/backend/utils/statistics.js

85 lines
2.6 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

const Post = require('../models/Post');
const User = require('../models/User');
// Увеличить счётчик просмотров поста
async function incrementPostViews(postId) {
try {
await Post.findByIdAndUpdate(postId, { $inc: { views: 1 } });
} catch (error) {
console.error('Ошибка увеличения просмотров:', error);
}
}
// Получить статистику пользователя
async function getUserStatistics(userId) {
try {
const user = await User.findById(userId);
if (!user) {
return null;
}
// Количество постов
const postsCount = await Post.countDocuments({ author: userId });
// Все посты пользователя
const userPosts = await Post.find({ author: userId });
// Общее количество лайков
const totalLikes = userPosts.reduce((sum, post) => sum + post.likes.length, 0);
// Общее количество комментариев
const totalComments = userPosts.reduce((sum, post) => sum + post.comments.length, 0);
// Общее количество просмотров
const totalViews = userPosts.reduce((sum, post) => sum + (post.views || 0), 0);
// Средняя вовлечённость (engagement rate)
const totalEngagement = totalLikes + totalComments;
const engagementRate = totalViews > 0 ? (totalEngagement / totalViews * 100).toFixed(2) : 0;
return {
postsCount,
followersCount: user.followers.length,
followingCount: user.following.length,
totalLikes,
totalComments,
totalViews,
totalEngagement,
engagementRate: parseFloat(engagementRate)
};
} catch (error) {
console.error('Ошибка получения статистики:', error);
return null;
}
}
// Получить топ посты пользователя
async function getUserTopPosts(userId, limit = 5) {
try {
const posts = await Post.find({ author: userId })
.sort({ views: -1 })
.limit(limit)
.populate('author', 'username firstName lastName photoUrl');
return posts.map(post => ({
id: post._id,
content: post.content ? post.content.substring(0, 100) : '',
likes: post.likes.length,
comments: post.comments.length,
views: post.views || 0,
createdAt: post.createdAt
}));
} catch (error) {
console.error('Ошибка получения топ постов:', error);
return [];
}
}
module.exports = {
incrementPostViews,
getUserStatistics,
getUserTopPosts
};