second-project-wahm3i/helpers/groceryitem_helpers.py

61 lines
1.7 KiB
Python

from typing import Optional, Dict, Any
from uuid import UUID
from sqlalchemy.orm import Session
from models.grocery_item import GroceryItem
from fastapi import HTTPException
def get_grocery_item_id_by_name(db: Session, name: str) -> Optional[UUID]:
"""
Retrieves the ID of a grocery item based on its name.
Args:
db (Session): The database session.
name (str): The name of the grocery item to search for.
Returns:
Optional[UUID]: The ID of the grocery item if found, None otherwise.
Raises:
HTTPException: If the name is empty or None.
"""
if not name or not name.strip():
raise HTTPException(status_code=400, detail="Grocery item name cannot be empty")
grocery_item = db.query(GroceryItem).filter(GroceryItem.name == name.strip()).first()
return grocery_item.id if grocery_item else None
def validate_grocery_item_name(name: str) -> bool:
"""
Validates the grocery item name.
Args:
name (str): The name to validate.
Returns:
bool: True if the name is valid, False otherwise.
"""
if not name or not isinstance(name, str):
return False
# Remove leading/trailing whitespace and check length
cleaned_name = name.strip()
if len(cleaned_name) < 1 or len(cleaned_name) > 100: # Assuming reasonable length limits
return False
return True
def format_grocery_item_response(item_id: UUID, name: str) -> Dict[str, Any]:
"""
Formats the grocery item response data.
Args:
item_id (UUID): The ID of the grocery item.
name (str): The name of the grocery item.
Returns:
Dict[str, Any]: Formatted response dictionary.
"""
return {
"id": str(item_id),
"name": name
}