2026-01-26 11:09:40 -05:00

53 lines
2.2 KiB
Python

from typing import AsyncGenerator
import strawberry
from channels.db import database_sync_to_async
from strawberry.types import Info
from core.graphql.pubsub import pubsub
from core.graphql.types.account import AccountType
from core.graphql.utils import _extract_id
from core.models.account import Account
@strawberry.type
class Subscription:
@strawberry.subscription(description="Subscribe to account creation events")
async def account_created(self, info: Info) -> AsyncGenerator[AccountType, None]:
user = info.context.user
if not user or not user.is_authenticated:
raise PermissionError("Authentication required")
async with pubsub.subscribe("account_created") as subscriber:
async for payload in subscriber:
account_id = await _extract_id(payload)
try:
instance = await database_sync_to_async(Account.objects.get)(pk=account_id)
except Account.DoesNotExist:
continue
yield instance
@strawberry.subscription(description="Subscribe to account updates")
async def account_updated(self, info: Info) -> AsyncGenerator[AccountType, None]:
user = info.context.user
if not user or not user.is_authenticated:
raise PermissionError("Authentication required")
async with pubsub.subscribe("account_updated") as subscriber:
async for payload in subscriber:
account_id = await _extract_id(payload)
try:
instance = await database_sync_to_async(Account.objects.get)(pk=account_id)
except Account.DoesNotExist:
continue
yield instance
@strawberry.subscription(description="Subscribe to account deletion events")
async def account_deleted(self, info: Info) -> AsyncGenerator[strawberry.ID, None]:
user = info.context.user
if not user or not user.is_authenticated:
raise PermissionError("Authentication required")
async with pubsub.subscribe("account_deleted") as subscriber:
async for payload in subscriber:
account_id = await _extract_id(payload)
yield strawberry.ID(account_id)