Source code for services.users.followers

from apps.users.models import User
from services.notifications.notification import NotificationService
from services.users.exceptions import AlreadyFollowingUserException, NotFollowingUserException


[docs] class FollowersService: """ Service class for managing followers for a user. This class contains methods to handle following and unfollowing operations for a user. It ensures that the operations are valid and raises exceptions if they are not. Attributes: _user (User): The user who is performing the follow or unfollow operation. """ notification_service = NotificationService
[docs] def __init__(self, user: User): self._user = user
def _validate_follow(self, following_user: User) -> None: """ Validate if the follow operation is permissible. """ if self._user.following.filter(pk=following_user.pk).exists(): raise AlreadyFollowingUserException
[docs] def follow(self, following_user: User) -> None: """ Follow a user. This method adds the given following_user to the user's following list after validating the operation using _validate_follow. Args: following_user (User): The user to follow. """ self._validate_follow(following_user) self._user.following.add(following_user) self.notification_service.send_follow_notification(sender=self._user, receiver=following_user)
def _validate_unfollow(self, following_user: User) -> None: """ Validate if the unfollow operation is permissible. """ if not self._user.following.filter(pk=following_user.pk).exists(): raise NotFollowingUserException
[docs] def unfollow(self, following_user: User): """ Unfollow a user. This method removes the given following_user from the user's following list after validating the operation using _validate_unfollow. Args: following_user (User): The user to unfollow. """ self._validate_unfollow(following_user) self._user.following.remove(following_user)