refactors

This commit is contained in:
counterweight 2025-12-25 18:27:59 +01:00
parent f46d2ae8b3
commit 168b67acee
Signed by: counterweight
GPG key ID: 883EDBAA726BD96C
12 changed files with 471 additions and 126 deletions

View file

@ -0,0 +1,32 @@
"""Utilities for validating enum values from strings."""
from enum import Enum
from typing import TypeVar
from exceptions import BadRequestError
T = TypeVar("T", bound=Enum)
def validate_enum(enum_class: type[T], value: str, field_name: str = "value") -> T:
"""
Validate and convert string to enum.
Args:
enum_class: The enum class to validate against
value: The string value to validate
field_name: Name of the field for error messages
Returns:
The validated enum value
Raises:
BadRequestError: If the value is not a valid enum member
"""
try:
return enum_class(value)
except ValueError:
valid_values = ", ".join(e.value for e in enum_class)
raise BadRequestError(
f"Invalid {field_name}: {value}. Must be one of: {valid_values}"
) from None