From e0fb934a7e1b2ae05915f1162c2ad512a9db682a Mon Sep 17 00:00:00 2001 From: Peter Vacho Date: Sun, 29 Dec 2024 17:43:31 +0100 Subject: [PATCH] Add endpoint to mark notifications as read --- src/api/notifications.py | 23 ++++++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) diff --git a/src/api/notifications.py b/src/api/notifications.py index 9f91c1c..0a0d500 100644 --- a/src/api/notifications.py +++ b/src/api/notifications.py @@ -1,4 +1,4 @@ -from datetime import datetime +from datetime import UTC, datetime from typing import Any, Literal, cast, final from beanie import Link, PydanticObjectId @@ -89,6 +89,27 @@ async def get_notification(notification_id: PydanticObjectId, user: CurrentUserD return NotificationData.from_notification(notification) +@notifications_router.get("{notification_id}/read") +async def read_notification(notification_id: PydanticObjectId, user: CurrentUserDep) -> NotificationData: + """Mark a notification as read.""" + notification = await Notification.get(notification_id, fetch_links=True) + + if notification is None: + raise HTTPException(status.HTTP_404_NOT_FOUND, "Notification not found.") + + if user.id is None: + raise MissingIdError(user) + + if cast(User, notification.user).id != user.id: + raise HTTPException(status.HTTP_403_FORBIDDEN, "You can only access your own notifications.") + + notification.read = True + notification.read_at = datetime.now(UTC) + notification = await notification.replace() + + return NotificationData.from_notification(notification) + + router = APIRouter() router.include_router(base_router) router.include_router(notifications_router)