82 lines
2.0 KiB
Python
82 lines
2.0 KiB
Python
from typing import Any, Dict, List, Optional, Union
|
|
|
|
from fastapi.encoders import jsonable_encoder
|
|
from sqlalchemy.orm import Session
|
|
|
|
from app.models.category import Category
|
|
from app.schemas.category import CategoryCreate, CategoryUpdate
|
|
from app.utils.uuid import generate_uuid
|
|
|
|
|
|
def get(db: Session, category_id: str) -> Optional[Category]:
|
|
"""
|
|
Get a category by ID.
|
|
"""
|
|
return db.query(Category).filter(Category.id == category_id).first()
|
|
|
|
|
|
def get_by_name(db: Session, name: str) -> Optional[Category]:
|
|
"""
|
|
Get a category by name.
|
|
"""
|
|
return db.query(Category).filter(Category.name == name).first()
|
|
|
|
|
|
def get_multi(
|
|
db: Session, *, skip: int = 0, limit: int = 100, name: Optional[str] = None
|
|
) -> List[Category]:
|
|
"""
|
|
Get multiple categories with optional filtering by name.
|
|
"""
|
|
query = db.query(Category)
|
|
|
|
if name:
|
|
query = query.filter(Category.name.ilike(f"%{name}%"))
|
|
|
|
return query.offset(skip).limit(limit).all()
|
|
|
|
|
|
def create(db: Session, *, obj_in: CategoryCreate) -> Category:
|
|
"""
|
|
Create a new category.
|
|
"""
|
|
obj_in_data = jsonable_encoder(obj_in)
|
|
db_obj = Category(**obj_in_data, id=generate_uuid())
|
|
db.add(db_obj)
|
|
db.commit()
|
|
db.refresh(db_obj)
|
|
return db_obj
|
|
|
|
|
|
def update(
|
|
db: Session, *, db_obj: Category, obj_in: Union[CategoryUpdate, Dict[str, Any]]
|
|
) -> Category:
|
|
"""
|
|
Update a category.
|
|
"""
|
|
obj_data = jsonable_encoder(db_obj)
|
|
if isinstance(obj_in, dict):
|
|
update_data = obj_in
|
|
else:
|
|
update_data = obj_in.model_dump(exclude_unset=True)
|
|
|
|
for field in obj_data:
|
|
if field in update_data:
|
|
setattr(db_obj, field, update_data[field])
|
|
|
|
db.add(db_obj)
|
|
db.commit()
|
|
db.refresh(db_obj)
|
|
return db_obj
|
|
|
|
|
|
def remove(db: Session, *, category_id: str) -> Optional[Category]:
|
|
"""
|
|
Delete a category.
|
|
"""
|
|
obj = db.query(Category).get(category_id)
|
|
if obj:
|
|
db.delete(obj)
|
|
db.commit()
|
|
return obj
|