Untitled

mail@pastecode.io avatar
unknown
plain_text
a month ago
1.7 kB
2
Indexable
Never
from pprint import pp
from typing import Annotated

from fastapi import BackgroundTasks, Depends, Header
from sqlalchemy import select
from sqlalchemy.orm import Session
from strawberry.dataloader import DataLoader
from strawberry.fastapi import BaseContext

from app.dependencies import current_user, get_db
from app.helpers.custom_logger import get_backend_logger
from app.models import User

from .loaders import UserLoader


class Context(BaseContext):
    """
    Represents the context for GraphQL resolvers.

    Args:
        current_user (str | None): The current user.
        session (Session): The database session.

    Attributes:
        current_user (int | None): The ID of the current user.
        session (Session): The database session.
    """

    def __init__(
        self,
        current_user: str | None,
        session: Session,
        background_tasks: BackgroundTasks,
    ):
        self.current_user = None
        self.session = session
        self.background_tasks = background_tasks
        self.backend_logger = get_backend_logger()
        if current_user is not None:
            self.current_user = session.scalar(
                select(User.id).filter(User.email.ilike(current_user))
            )

        # Create all the data loaders for this context
        self.load_user = DataLoader(load_fn=UserLoader(session))


def context_dependency(
    current_user: Annotated[current_user, Depends()],
    session: Annotated[get_db, Depends()],
    background_tasks: BackgroundTasks,
) -> Context:
    return Context(current_user, session, background_tasks)


def get_context(context: Annotated[context_dependency, Depends()]):
    return context
Leave a Comment