nakama/backend/routes/notifications.js

131 lines
3.9 KiB
JavaScript
Raw Permalink 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 express = require('express');
const router = express.Router();
const { authenticate } = require('../middleware/auth');
const { log } = require('../middleware/logger');
const Notification = require('../models/Notification');
// Получить уведомления пользователя
router.get('/', authenticate, async (req, res) => {
try {
const { page = 1, limit = 50 } = req.query;
log('info', 'Загрузка уведомлений', {
userId: req.user._id,
username: req.user.username,
page,
limit
});
const notifications = await Notification.find({ recipient: req.user._id })
.populate('sender', 'username firstName lastName photoUrl')
.populate('post', 'content imageUrl images')
.sort({ createdAt: -1 })
.limit(limit * 1)
.skip((page - 1) * limit)
.exec();
const count = await Notification.countDocuments({ recipient: req.user._id });
const unreadCount = await Notification.countDocuments({
recipient: req.user._id,
read: false
});
log('info', 'Уведомления загружены', {
userId: req.user._id,
count: notifications.length,
total: count,
unread: unreadCount
});
res.json({
notifications,
totalPages: Math.ceil(count / limit),
currentPage: page,
unreadCount
});
} catch (error) {
log('error', 'Ошибка получения уведомлений', {
userId: req.user?._id,
error: error.message,
stack: error.stack
});
res.status(500).json({ error: 'Ошибка сервера' });
}
});
// Отметить уведомление как прочитанное
router.put('/:id/read', authenticate, async (req, res) => {
try {
log('info', 'Отметка уведомления как прочитанное', {
userId: req.user._id,
notificationId: req.params.id
});
const notification = await Notification.findOne({
_id: req.params.id,
recipient: req.user._id
});
if (!notification) {
log('warn', 'Уведомление не найдено', {
userId: req.user._id,
notificationId: req.params.id
});
return res.status(404).json({ error: 'Уведомление не найдено' });
}
notification.read = true;
await notification.save();
log('info', 'Уведомление отмечено как прочитанное', {
userId: req.user._id,
notificationId: req.params.id
});
res.json({ message: 'Уведомление прочитано' });
} catch (error) {
log('error', 'Ошибка обновления уведомления', {
userId: req.user?._id,
notificationId: req.params.id,
error: error.message,
stack: error.stack
});
res.status(500).json({ error: 'Ошибка сервера' });
}
});
// Отметить все уведомления как прочитанные
router.put('/read-all', authenticate, async (req, res) => {
try {
log('info', 'Отметка всех уведомлений как прочитанные', {
userId: req.user._id,
username: req.user.username
});
const result = await Notification.updateMany(
{ recipient: req.user._id, read: false },
{ read: true }
);
log('info', 'Все уведомления отмечены', {
userId: req.user._id,
updated: result.modifiedCount
});
res.json({
message: 'Все уведомления прочитаны',
updated: result.modifiedCount
});
} catch (error) {
log('error', 'Ошибка обновления уведомлений', {
userId: req.user?._id,
error: error.message,
stack: error.stack
});
res.status(500).json({ error: 'Ошибка сервера' });
}
});
module.exports = router;