Skip to content

Commit

Permalink
feat(notification): Added events
Browse files Browse the repository at this point in the history
  • Loading branch information
Topvennie committed Mar 6, 2024
1 parent 55ff80f commit 6a24fa1
Show file tree
Hide file tree
Showing 3 changed files with 50 additions and 4 deletions.
16 changes: 13 additions & 3 deletions backend/notifications/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
34 changes: 34 additions & 0 deletions backend/notifications/signals.py
Original file line number Diff line number Diff line change
@@ -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
4 changes: 3 additions & 1 deletion backend/notifications/urls.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
from django.urls import path
from notifications.views import NotificationView

urlpatterns = [path("<str:user_id>/", NotificationView.as_view())]
urlpatterns = [
path("<str:user_id>/", NotificationView.as_view()),
]

0 comments on commit 6a24fa1

Please sign in to comment.