juicy-backend-4vskhl/helpers/generic_helpers.py

87 lines
2.5 KiB
Python

from typing import Dict, Any, List, Optional
from pydantic import BaseModel
# In-memory store since no model code was provided
_countries_store: List[Dict[str, Any]] = []
class CountryData(BaseModel):
name: str
color: str
def validate_country_data(country_data: Dict[str, Any]) -> bool:
"""
Validates the country data before adding to store.
Args:
country_data (Dict[str, Any]): The country data to validate.
Returns:
bool: True if data is valid, False otherwise.
"""
if not isinstance(country_data.get("name"), str) or not country_data.get("name").strip():
return False
if not isinstance(country_data.get("color"), str) or not country_data.get("color").strip():
return False
return True
def create_country(country_data: CountryData) -> Dict[str, Any]:
"""
Adds a new country to the in-memory store.
Args:
country_data (CountryData): The country data to add.
Returns:
Dict[str, Any]: The created country data.
"""
country_dict = country_data.dict()
if not validate_country_data(country_dict):
raise ValueError("Invalid country data provided")
# Check for duplicate country names
if any(country["name"].lower() == country_dict["name"].lower() for country in _countries_store):
raise ValueError("Country with this name already exists")
_countries_store.append(country_dict)
return country_dict
def get_all_countries() -> List[Dict[str, Any]]:
"""
Retrieves all countries from the in-memory store.
Returns:
List[Dict[str, Any]]: List of all countries.
"""
return _countries_store
def get_country_by_name(name: str) -> Optional[Dict[str, Any]]:
"""
Retrieves a country by its name.
Args:
name (str): The name of the country to find.
Returns:
Optional[Dict[str, Any]]: The country if found, otherwise None.
"""
for country in _countries_store:
if country["name"].lower() == name.lower():
return country
return None
def update_country_color(name: str, new_color: str) -> Optional[Dict[str, Any]]:
"""
Updates the color of an existing country.
Args:
name (str): The name of the country to update.
new_color (str): The new color to set.
Returns:
Optional[Dict[str, Any]]: The updated country if found, otherwise None.
"""
for country in _countries_store:
if country["name"].lower() == name.lower():
country["color"] = new_color
return country
return None