2025-03-28 09:41:25 +00:00

107 lines
2.9 KiB
Python

from typing import List, Dict, Optional
from datetime import datetime
from fastapi import HTTPException
from models.meal import Meal
from schemas.meal import MealCreate, MealUpdate
def validate_meal_name(name: str) -> bool:
"""
Validate the meal name.
Args:
name (str): The meal name to validate.
Returns:
bool: True if the meal name is valid, False otherwise.
"""
return bool(name.strip())
def get_available_meals(db_session) -> List[Meal]:
"""
Get the list of available meals from the database.
Args:
db_session: The database session.
Returns:
List[Meal]: A list of available meals.
"""
return db_session.query(Meal).filter(Meal.is_available == True).all()
def get_meal_by_id(db_session, meal_id: int) -> Optional[Meal]:
"""
Get a meal by its ID from the database.
Args:
db_session: The database session.
meal_id (int): The ID of the meal to retrieve.
Returns:
Optional[Meal]: The meal object if found, None otherwise.
"""
return db_session.query(Meal).filter(Meal.id == meal_id).first()
def create_meal(db_session, meal_data: MealCreate) -> Meal:
"""
Create a new meal in the database.
Args:
db_session: The database session.
meal_data (MealCreate): The data for creating a new meal.
Returns:
Meal: The created meal object.
Raises:
HTTPException: If the meal name is invalid.
"""
if not validate_meal_name(meal_data.name):
raise HTTPException(status_code=400, detail="Invalid meal name")
new_meal = Meal(
name=meal_data.name,
description=meal_data.description,
price=meal_data.price,
is_available=meal_data.is_available,
created_at=datetime.utcnow(),
updated_at=datetime.utcnow(),
)
db_session.add(new_meal)
db_session.commit()
db_session.refresh(new_meal)
return new_meal
def update_meal(db_session, meal_id: int, meal_data: MealUpdate) -> Optional[Meal]:
"""
Update an existing meal in the database.
Args:
db_session: The database session.
meal_id (int): The ID of the meal to update.
meal_data (MealUpdate): The updated data for the meal.
Returns:
Optional[Meal]: The updated meal object if found, None otherwise.
Raises:
HTTPException: If the meal name is invalid.
"""
meal = get_meal_by_id(db_session, meal_id)
if not meal:
return None
if not validate_meal_name(meal_data.name):
raise HTTPException(status_code=400, detail="Invalid meal name")
meal.name = meal_data.name or meal.name
meal.description = meal_data.description or meal.description
meal.price = meal_data.price or meal.price
meal.is_available = meal_data.is_available or meal.is_available
meal.updated_at = datetime.utcnow()
db_session.commit()
db_session.refresh(meal)
return meal