Untitled

 avatar
unknown
plain_text
5 months ago
4.9 kB
3
Indexable
from fastapi import FastAPI, Depends, HTTPException
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, Session
import strawberry
from strawberry.fastapi import GraphQLRouter
from pydantic import BaseModel

# Database setup
DATABASE_URL = "sqlite:///./test.db"  # Change this to your database URL

engine = create_engine(DATABASE_URL)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()

# Models
class ProductCategory(Base):
    __tablename__ = 'product_category'  # Specify your table name

    mdm_id = Column(Integer, primary_key=True, autoincrement=True)
    prod_cat_grp = Column(String, nullable=False)
    category_id = Column(Integer, nullable=False)
    ta_sub_type = Column(String, nullable=False)

    def __repr__(self):
        return f"<ProductCategory(mdm_id={self.mdm_id}, prod_cat_grp='{self.prod_cat_grp}', category_id={self.category_id}, ta_sub_type='{self.ta_sub_type}')>"

# Create the database tables
Base.metadata.create_all(bind=engine)

# Pydantic schemas
class ProductCategorySchema(BaseModel):
    mdm_id: int
    prod_cat_grp: str
    category_id: int
    ta_sub_type: str

    class Config:
        orm_mode = True

# Exceptions
class CategoryException(Exception):
    def __init__(self, message: str):
        super().__init__(message)

# Services
class ProductCategoryService:
    def __init__(self, db: Session):
        self.db = db

    def create_category(self, category: ProductCategorySchema) -> ProductCategory:
        new_category = ProductCategory(
            prod_cat_grp=category.prod_cat_grp,
            category_id=category.category_id,
            ta_sub_type=category.ta_sub_type
        )
        self.db.add(new_category)
        self.db.commit()
        self.db.refresh(new_category)
        return new_category

    def update_category(self, mdm_id: int, category: ProductCategorySchema) -> ProductCategory:
        db_category = self.db.query(ProductCategory).filter(ProductCategory.mdm_id == mdm_id).first()
        if db_category is None:
            raise CategoryException("Category not found.")
        db_category.prod_cat_grp = category.prod_cat_grp
        db_category.category_id = category.category_id
        db_category.ta_sub_type = category.ta_sub_type
        self.db.commit()
        self.db.refresh(db_category)
        return db_category

    def get_category(self, mdm_id: int) -> ProductCategory:
        category = self.db.query(ProductCategory).filter(ProductCategory.mdm_id == mdm_id).first()
        if category is None:
            raise CategoryException("Category not found.")
        return category

    def delete_category(self, mdm_id: int) -> None:
        db_category = self.db.query(ProductCategory).filter(ProductCategory.mdm_id == mdm_id).first()
        if db_category is None:
            raise CategoryException("Category not found.")
        self.db.delete(db_category)
        self.db.commit()

# GraphQL schema
@strawberry.type
class Query:
    @strawberry.field
    def get_category(self, mdm_id: int, db: Session = Depends(SessionLocal)) -> ProductCategorySchema:
        service = ProductCategoryService(db)
        category = service.get_category(mdm_id)
        return ProductCategorySchema.from_orm(category)

    @strawberry.field
    def list_categories(self, db: Session = Depends(SessionLocal)) -> list[ProductCategorySchema]:
        service = ProductCategoryService(db)
        categories = service.db.query(ProductCategory).all()
        return [ProductCategorySchema.from_orm(category) for category in categories]

@strawberry.type
class Mutation:
    @strawberry.mutation
    def create_category(self, category: ProductCategorySchema, db: Session = Depends(SessionLocal)) -> ProductCategorySchema:
        service = ProductCategoryService(db)
        created_category = service.create_category(category)
        return ProductCategorySchema.from_orm(created_category)

    @strawberry.mutation
    def update_category(self, mdm_id: int, category: ProductCategorySchema, db: Session = Depends(SessionLocal)) -> ProductCategorySchema:
        service = ProductCategoryService(db)
        updated_category = service.update_category(mdm_id, category)
        return ProductCategorySchema.from_orm(updated_category)

    @strawberry.mutation
    def delete_category(self, mdm_id: int, db: Session = Depends(SessionLocal)) -> str:
        service = ProductCategoryService(db)
        service.delete_category(mdm_id)
        return "Category deleted successfully."

# FastAPI app setup
app = FastAPI()
graphql_app = GraphQLRouter(strawberry.Schema(query=Query, mutation=Mutation))
app.include_router(graphql_app, prefix="/graphql")

# Dependency to get the database session
def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()
Editor is loading...
Leave a Comment