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.project import ProjectType
from core.graphql.utils import _extract_id
from core.models.project import Project
@strawberry.type
class Subscription:
@strawberry.subscription(description="Subscribe to project creation events")
async def project_created(self, info: Info) -> AsyncGenerator[ProjectType, None]:
user = info.context.user
if not user or not user.is_authenticated:
raise PermissionError("Authentication required")
async with pubsub.subscribe("project_created") as subscriber:
async for payload in subscriber:
project_id = await _extract_id(payload)
try:
instance = await database_sync_to_async(Project.objects.get)(pk=project_id)
except Project.DoesNotExist:
continue
yield instance
@strawberry.subscription(description="Subscribe to project updates")
async def project_updated(self, info: Info) -> AsyncGenerator[ProjectType, None]:
user = info.context.user
if not user or not user.is_authenticated:
raise PermissionError("Authentication required")
async with pubsub.subscribe("project_updated") as subscriber:
async for payload in subscriber:
project_id = await _extract_id(payload)
try:
instance = await database_sync_to_async(Project.objects.get)(pk=project_id)
except Project.DoesNotExist:
continue
yield instance
@strawberry.subscription(description="Subscribe to project deletion events")
async def project_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("project_deleted") as subscriber:
async for payload in subscriber:
project_id = await _extract_id(payload)
yield strawberry.ID(project_id)