106 lines
2.8 KiB
Python
106 lines
2.8 KiB
Python
from typing import Dict, Any, List, Optional
|
|
import uuid
|
|
from datetime import datetime
|
|
|
|
# In-memory storage for cars
|
|
_cars_store: List[Dict[str, Any]] = []
|
|
|
|
def validate_car_data(car_data: Dict[str, Any]) -> bool:
|
|
"""
|
|
Validates the input car data.
|
|
|
|
Args:
|
|
car_data (Dict[str, Any]): The car data to validate.
|
|
|
|
Returns:
|
|
bool: True if data is valid, False otherwise.
|
|
"""
|
|
if not isinstance(car_data, dict):
|
|
return False
|
|
|
|
required_fields = ['name', 'color']
|
|
if not all(field in car_data for field in required_fields):
|
|
return False
|
|
|
|
if not isinstance(car_data['name'], str) or len(car_data['name'].strip()) == 0:
|
|
return False
|
|
|
|
if not isinstance(car_data['color'], str) or len(car_data['color'].strip()) == 0:
|
|
return False
|
|
|
|
return True
|
|
|
|
def create_car(car_data: Dict[str, Any]) -> Dict[str, Any]:
|
|
"""
|
|
Creates a new car entry in the in-memory storage.
|
|
|
|
Args:
|
|
car_data (Dict[str, Any]): The car data containing name and color.
|
|
|
|
Returns:
|
|
Dict[str, Any]: The created car data with generated ID and timestamps.
|
|
|
|
Raises:
|
|
ValueError: If the car data is invalid.
|
|
"""
|
|
if not validate_car_data(car_data):
|
|
raise ValueError("Invalid car data provided")
|
|
|
|
new_car = {
|
|
"id": str(uuid.uuid4()),
|
|
"name": car_data["name"].strip(),
|
|
"color": car_data["color"].strip(),
|
|
"created_at": datetime.utcnow(),
|
|
"updated_at": datetime.utcnow()
|
|
}
|
|
|
|
_cars_store.append(new_car)
|
|
return new_car
|
|
|
|
def get_car_by_id(car_id: str) -> Optional[Dict[str, Any]]:
|
|
"""
|
|
Retrieves a car by its ID from the in-memory storage.
|
|
|
|
Args:
|
|
car_id (str): The ID of the car to retrieve.
|
|
|
|
Returns:
|
|
Optional[Dict[str, Any]]: The car data if found, None otherwise.
|
|
"""
|
|
return next((car for car in _cars_store if car["id"] == car_id), None)
|
|
|
|
def get_all_cars() -> List[Dict[str, Any]]:
|
|
"""
|
|
Retrieves all cars from the in-memory storage.
|
|
|
|
Returns:
|
|
List[Dict[str, Any]]: List of all stored cars.
|
|
"""
|
|
return _cars_store
|
|
|
|
def search_cars_by_color(color: str) -> List[Dict[str, Any]]:
|
|
"""
|
|
Searches for cars by color in the in-memory storage.
|
|
|
|
Args:
|
|
color (str): The color to search for.
|
|
|
|
Returns:
|
|
List[Dict[str, Any]]: List of cars matching the specified color.
|
|
"""
|
|
return [car for car in _cars_store if car["color"].lower() == color.lower()]
|
|
|
|
def normalize_car_data(car_data: Dict[str, Any]) -> Dict[str, Any]:
|
|
"""
|
|
Normalizes car data by trimming whitespace and converting to proper case.
|
|
|
|
Args:
|
|
car_data (Dict[str, Any]): The car data to normalize.
|
|
|
|
Returns:
|
|
Dict[str, Any]: Normalized car data.
|
|
"""
|
|
return {
|
|
"name": car_data["name"].strip(),
|
|
"color": car_data["color"].strip().lower()
|
|
} |