77 lines
2.0 KiB
Python
77 lines
2.0 KiB
Python
from typing import Optional
|
|
from sqlalchemy.orm import Session
|
|
from sqlalchemy.exc import IntegrityError
|
|
from models.fruit import Fruit
|
|
from schemas.fruit import FruitCreate, FruitSchema
|
|
|
|
def create_fruit(db: Session, fruit_data: FruitCreate) -> Optional[Fruit]:
|
|
"""
|
|
Creates a new fruit in the database.
|
|
|
|
Args:
|
|
db (Session): The database session.
|
|
fruit_data (FruitCreate): The data for the fruit to create.
|
|
|
|
Returns:
|
|
Optional[Fruit]: The newly created fruit object, or None if creation fails.
|
|
"""
|
|
try:
|
|
db_fruit = Fruit(name=fruit_data.name)
|
|
db.add(db_fruit)
|
|
db.commit()
|
|
db.refresh(db_fruit)
|
|
return db_fruit
|
|
except IntegrityError:
|
|
db.rollback()
|
|
return None
|
|
|
|
def get_fruit_by_name(db: Session, name: str) -> Optional[Fruit]:
|
|
"""
|
|
Retrieves a fruit by its name.
|
|
|
|
Args:
|
|
db (Session): The database session.
|
|
name (str): The name of the fruit to retrieve.
|
|
|
|
Returns:
|
|
Optional[Fruit]: The fruit object if found, otherwise None.
|
|
"""
|
|
return db.query(Fruit).filter(Fruit.name == name).first()
|
|
|
|
def validate_fruit_name(name: str) -> bool:
|
|
"""
|
|
Validates the fruit name according to business rules.
|
|
|
|
Args:
|
|
name (str): The fruit name to validate.
|
|
|
|
Returns:
|
|
bool: True if the name is valid, False otherwise.
|
|
"""
|
|
if not name or not isinstance(name, str):
|
|
return False
|
|
|
|
# Remove whitespace and check length
|
|
cleaned_name = name.strip()
|
|
if len(cleaned_name) < 1:
|
|
return False
|
|
|
|
# Additional validation rules could be added here
|
|
return True
|
|
|
|
def format_fruit_response(fruit: Fruit) -> FruitSchema:
|
|
"""
|
|
Formats a fruit database object into a response schema.
|
|
|
|
Args:
|
|
fruit (Fruit): The fruit database object to format.
|
|
|
|
Returns:
|
|
FruitSchema: The formatted fruit response.
|
|
"""
|
|
return FruitSchema(
|
|
id=fruit.id,
|
|
name=fruit.name,
|
|
created_at=fruit.created_at,
|
|
updated_at=fruit.updated_at
|
|
) |