76 lines
2.4 KiB
JavaScript
76 lines
2.4 KiB
JavaScript
const express = require('express');
|
||
const router = express.Router();
|
||
const { authenticate } = require('../middleware/auth');
|
||
const Notification = require('../models/Notification');
|
||
|
||
// Получить уведомления пользователя
|
||
router.get('/', authenticate, async (req, res) => {
|
||
try {
|
||
const { page = 1, limit = 50 } = req.query;
|
||
|
||
const notifications = await Notification.find({ recipient: req.user._id })
|
||
.populate('sender', 'username firstName lastName photoUrl')
|
||
.populate('post', 'content imageUrl')
|
||
.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
|
||
});
|
||
|
||
res.json({
|
||
notifications,
|
||
totalPages: Math.ceil(count / limit),
|
||
currentPage: page,
|
||
unreadCount
|
||
});
|
||
} catch (error) {
|
||
console.error('Ошибка получения уведомлений:', error);
|
||
res.status(500).json({ error: 'Ошибка сервера' });
|
||
}
|
||
});
|
||
|
||
// Отметить уведомление как прочитанное
|
||
router.put('/:id/read', authenticate, async (req, res) => {
|
||
try {
|
||
const notification = await Notification.findOne({
|
||
_id: req.params.id,
|
||
recipient: req.user._id
|
||
});
|
||
|
||
if (!notification) {
|
||
return res.status(404).json({ error: 'Уведомление не найдено' });
|
||
}
|
||
|
||
notification.read = true;
|
||
await notification.save();
|
||
|
||
res.json({ message: 'Уведомление прочитано' });
|
||
} catch (error) {
|
||
console.error('Ошибка обновления уведомления:', error);
|
||
res.status(500).json({ error: 'Ошибка сервера' });
|
||
}
|
||
});
|
||
|
||
// Отметить все уведомления как прочитанные
|
||
router.put('/read-all', authenticate, async (req, res) => {
|
||
try {
|
||
await Notification.updateMany(
|
||
{ recipient: req.user._id, read: false },
|
||
{ read: true }
|
||
);
|
||
|
||
res.json({ message: 'Все уведомления прочитаны' });
|
||
} catch (error) {
|
||
console.error('Ошибка обновления уведомлений:', error);
|
||
res.status(500).json({ error: 'Ошибка сервера' });
|
||
}
|
||
});
|
||
|
||
module.exports = router;
|
||
|