backend/routes/notification.js

56 lines
1.8 KiB
JavaScript
Raw Permalink Normal View History

2023-07-28 03:36:07 +00:00
const express = require('express');
const router = express.Router();
const Notification = require('../models/Notifications');
const jwt = require('jsonwebtoken');
const bcrypt = require('bcrypt');
function authenticate(req, res, next) {
const token = req.header('Authorization');
if (!token) return res.sendStatus(401);
jwt.verify(token, 'SECRET_KEY', (err, decoded) => {
if (err) return res.sendStatus(401);
req.userId = decoded.userId;
next();
});
}
// Fetch the 15 most recent notifications for the authenticated user
// Fetch notifications for the authenticated user, paginated
router.get('/notifications', authenticate, async (req, res) => {
// Parse the page number from the query string (default to 1 if not provided or invalid)
const page = parseInt(req.query.page) || 1;
console.log(req.query)
// Set the number of notifications per page
const pageSize = 15;
// Calculate the skip index (for the MongoDB query) based on the current page number and page size
const skipIndex = (page - 1) * pageSize;
const notifications = await Notification.find({ user: req.userId })
.sort({ read: 1, createdAt: -1 })
.skip(skipIndex)
.limit(pageSize);
res.json(notifications);
});
// Fetch a single notification by its ID (optional)
router.get('/notifications/:id', authenticate, async (req, res) => {
const notification = await Notification.findById(req.params.id);
if (!notification) return res.status(404).send('Notification not found');
res.json(notification);
});
// Mark a notification as read
router.put('/notifications/:id', authenticate, async (req, res) => {
const notification = await Notification.findById(req.params.id);
if (!notification) return res.status(404).send('Notification not found');
notification.read = true;
await notification.save();
res.json(notification);
});
module.exports = router;