Untitled

mail@pastecode.io avatar
unknown
plain_text
a month ago
6.8 kB
3
Indexable
Never
from datetime import datetime
from typing import List

from sqlalchemy import update
from strawberry import mutation, type

from app.dependencies.get_db import get_db
from app.graphql.schema import Info
from app.graphql.types.content_type import (
    ContentType,
    CreateContentInput,
    DeleteContentInput,
    UpdateContentInput,
)
from app.models import User
from app.models.content import Content


@type
class UpdateMutationPayload:
    contents: List[ContentType]
    success: bool
    message: str = ""


@type
class CreateMutationPayload:
    contents: List[ContentType]
    success: bool
    message: str = ""


@type
class DeleteMutationPayload:
    contents: List[ContentType]
    success: bool
    message: str = ""


@type
class ContentMutation:
    @mutation
    def update_contents(
        self, info: Info, input: List[UpdateContentInput]
    ) -> UpdateMutationPayload:
        # Use the context manager to manage the database session
        try:
            updated_contents_ids = []
            for content in input:
                stmt = (
                    update(Content)
                    .where(Content.id == content.id)
                    .values(
                        type=content.type,
                        text=content.text,
                        link=content.link,
                        order=content.order,
                        updated_date=datetime.now(),  # Automatically set to the current time
                    )
                )
                info.context.session.execute(stmt)
                updated_contents_ids.append(content.id)
            info.context.session.commit()
            updated_contents = info.context.session.query(Content).filter(Content.id.in_(updated_contents_ids)).all()
            updated_contents_graphql = [
                ContentType(
                    id=content.id,
                    type=content.type,
                    text=content.text,
                    link=content.link,
                    order=content.order,
                    created_date=content.created_date,
                    created_by=content.created_by,
                    updated_date=content.updated_date,
                    updated_by=content.updated_by,
                    is_deleted=content.is_deleted
                )
                for content in updated_contents
            ]
            return UpdateMutationPayload(
                contents=updated_contents_graphql, success=True, message="Content updated successfully"
            )
        except Exception as e:
            info.context.session.rollback()
            return UpdateMutationPayload(contents=[], success=False, message=f"Update failed: {str(e)}")

    @mutation
    def create_contents(
        self, info: Info, input: List[CreateContentInput]
    ) -> CreateMutationPayload:
        try:
            created_content_ids = []
            for content in input:
                new_content = Content(
                    type=content.type,
                    text=content.text,
                    link=content.link,
                    order=content.order,
                    created_date=datetime.now(),
                    updated_date=datetime.now(),
                )
                info.context.session.add(new_content)
                info.context.session.flush() #Ensures the new content gets an ID before commit
                created_content_ids.append(new_content.id)
            info.context.session.commit()
            created_contents = info.context.session.query(Content).filter(Content.id.in_(created_content_ids)).all()
            created_contents_graphql = [
                ContentType(
                    id=content.id,
                    type=content.type,
                    text=content.text,
                    link=content.link,
                    order=content.order,
                    created_date=content.created_date,
                    created_by=content.created_by,
                    updated_date=content.updated_date,
                    updated_by=content.updated_by,
                    is_deleted=content.is_deleted
                )
                for content in created_contents
            ]
            return CreateMutationPayload(
                contents=created_contents_graphql, success=True, message="Content created successfully"
            )
        except Exception as e:
            info.context.session.rollback()
            return CreateMutationPayload(contents=[], success=False, message=f"Creation failed: {str(e)}")

    @mutation
    def delete_contents(
        self, info: Info, input: List[DeleteContentInput]
    ) -> DeleteMutationPayload:
        try:
            deleted_content_ids = []
            for content in input:
                stmt = (
                    update(Content)
                    .where(Content.id == content.id)
                    .values(is_deleted=True)
                )
                
                result = info.context.session.execute(stmt)
                if result.rowcount > 0:
                    deleted_content_ids.append(content.id)
            info.context.session.commit()

            if deleted_content_ids:
                deleted_contents = info.context.session.query(Content).filter(Content.id.in_(deleted_content_ids)).all()
                deleted_contents_graphql = [
                    ContentType(
                        id=content.id,
                        type=content.type,
                        text=content.text,
                        link=content.link,
                        order=content.order,
                        created_date=content.created_date,
                        created_by=content.created_by,
                        updated_date=content.updated_date,
                        updated_by=content.updated_by,
                        is_deleted=True
                    )
                    for contents in deleted_contents
                ]
                return DeleteMutationPayload(
                    contents=deleted_contents_graphql,
                    success=True,
                    message=f"{len(deleted_content_ids)} content(s) deleted successfully",
                )
            else:
                return DeleteMutationPayload(
                    contents=[], success=False, message="No content was deleted"
                )
        except Exception as e:
            info.context.session.rollback()
            return DeleteMutationPayload(
                contents=[], success=False, message=f"Deletion failed: {str(e)}"
            )
Leave a Comment