farmcontrol-api/src/services/misc/notifications.js
Tom Butcher 3e47cb131b
Some checks failed
farmcontrol/farmcontrol-api/pipeline/head There was a failure building this commit
Implemented notifications.
2026-03-01 01:42:30 +00:00

106 lines
3.1 KiB
JavaScript

import config from '../../config.js';
import { notificationModel } from '../../database/schemas/misc/notification.schema.js';
import log4js from 'log4js';
import { listObjects, editObject } from '../../database/database.js';
const logger = log4js.getLogger('Notifications');
logger.level = config.server.logLevel;
export const listNotificationsRouteHandler = async (
req,
res,
page = 1,
limit = 50,
filter = {},
sort = 'createdAt',
order = 'descend'
) => {
const userFilter = { ...filter, user: req.user._id };
const result = await listObjects({
model: notificationModel,
page,
limit,
filter: userFilter,
sort,
order,
populate: [],
});
if (result?.error) {
logger.error('Error listing notifications.');
res.status(result.code || 500).send(result);
return;
}
logger.debug(`List of notifications (Page ${page}, Limit ${limit}). Count: ${result.length}`);
res.send(result);
};
export const markNotificationAsReadRouteHandler = async (req, res) => {
const id = req.params.id;
const existing = await notificationModel.findById(id).lean();
if (!existing) {
return res.status(404).send({ error: 'Notification not found' });
}
if (String(existing.user) !== String(req.user._id)) {
return res.status(403).send({ error: 'Forbidden: you can only update your own notifications' });
}
const result = await editObject({
model: notificationModel,
id,
updateData: { read: true, updatedAt: new Date() },
user: req.user,
});
if (result?.error) {
logger.error('Error marking notification as read:', result.error);
return res.status(result.code || 500).send(result);
}
logger.debug(`Marked notification as read: ${id}`);
res.send(result);
};
export const markAllNotificationsAsReadRouteHandler = async (req, res) => {
try {
await notificationModel.updateMany(
{ user: req.user._id, read: false },
{ $set: { read: true, updatedAt: new Date() } }
);
logger.debug('Marked all notifications as read');
res.send({ status: 'ok' });
} catch (err) {
logger.error('Error marking all notifications as read:', err);
res.status(500).send({ error: 'Failed to mark all as read' });
}
};
export const deleteNotificationRouteHandler = async (req, res) => {
const id = req.params.id;
const existing = await notificationModel.findById(id).lean();
if (!existing) {
return res.status(404).send({ error: 'Notification not found' });
}
if (String(existing.user._id) !== String(req.user._id)) {
return res.status(403).send({ error: 'Forbidden: you can only delete your own notifications' });
}
await notificationModel.findByIdAndDelete(id);
logger.debug('Deleted notification:', id);
res.send({ status: 'ok' });
};
export const deleteAllNotificationsRouteHandler = async (req, res) => {
try {
await notificationModel.deleteMany({ user: req.user._id });
logger.debug('Deleted all notifications');
res.send({ status: 'ok' });
} catch (err) {
logger.error('Error deleting all notifications:', err);
res.status(500).send({ error: 'Failed to delete all notifications' });
}
};