From 6a24fa1aae69470f9716661514f49a73b7c2724c Mon Sep 17 00:00:00 2001 From: Topvennie Date: Wed, 6 Mar 2024 13:44:10 +0100 Subject: [PATCH] feat(notification): Added events --- backend/notifications/serializers.py | 16 ++++++++++--- backend/notifications/signals.py | 34 ++++++++++++++++++++++++++++ backend/notifications/urls.py | 4 +++- 3 files changed, 50 insertions(+), 4 deletions(-) create mode 100644 backend/notifications/signals.py diff --git a/backend/notifications/serializers.py b/backend/notifications/serializers.py index 4a24cd59..52482ca9 100644 --- a/backend/notifications/serializers.py +++ b/backend/notifications/serializers.py @@ -13,11 +13,21 @@ class Meta: fields = "__all__" +# Hyper linked user field that returns a hyper link but expects an id +class UserHyperLinkedRelatedField(serializers.HyperlinkedRelatedField): + view_name = "user-detail" + queryset = User.objects.all() + + def to_internal_value(self, data): + try: + return self.queryset.get(pk=data) + except User.DoesNotExist: + self.fail("no_match") + + class NotificationSerializer(serializers.ModelSerializer): # Hyper linked user field - user = serializers.HyperlinkedRelatedField( - view_name="user-detail", queryset=User.objects.all() - ) + user = UserHyperLinkedRelatedField() # Translate template and arguments into a message message = serializers.SerializerMethodField() diff --git a/backend/notifications/signals.py b/backend/notifications/signals.py new file mode 100644 index 00000000..6abe6304 --- /dev/null +++ b/backend/notifications/signals.py @@ -0,0 +1,34 @@ +from __future__ import annotations + +import io +from enum import Enum +from typing import Dict + +from authentication.models import User +from django.dispatch import Signal, receiver +from notifications.models import Notification, NotificationTemplate +from notifications.serializers import NotificationSerializer +from rest_framework.parsers import JSONParser + +notification_create = Signal() + + +@receiver(notification_create) +def notification_creation( + type: NotificationType, user: User, arguments: Dict[str, str], **kwargs +) -> bool: + serializer = NotificationSerializer( + data={"template_id": type.value, "user": user.id, "arguments": arguments} + ) + + if not serializer.is_valid(): + return False + + serializer.save() + + return True + + +class NotificationType(Enum): + SCORE_ADDED = 1 + SCORE_UPDATED = 2 diff --git a/backend/notifications/urls.py b/backend/notifications/urls.py index 430a82b5..142fde10 100644 --- a/backend/notifications/urls.py +++ b/backend/notifications/urls.py @@ -1,4 +1,6 @@ from django.urls import path from notifications.views import NotificationView -urlpatterns = [path("/", NotificationView.as_view())] +urlpatterns = [ + path("/", NotificationView.as_view()), +]