diff --git a/src/app/schemas/pokemon.py b/src/app/schemas/pokemon.py index 7111dad..99c8fc4 100644 --- a/src/app/schemas/pokemon.py +++ b/src/app/schemas/pokemon.py @@ -1,10 +1,38 @@ """Pokemon module.""" +import functools import json +import logging from typing import Any from pydantic import BaseModel, ConfigDict, field_validator +logger = logging.getLogger(__name__) + + +@functools.lru_cache(maxsize=1024) +def _parse_types_json(value: str) -> tuple[str, ...]: + """Helper function to parse and cache the types JSON string. + + Args: + value: The value to parse, expected to be a JSON string. + + Returns: + An immutable tuple of parsed types. + + Raises: + ValueError: If the string is not valid JSON or not a list. + """ + try: + parsed = json.loads(value) + if not isinstance(parsed, list): + logger.error("invalid types format: expected list") + raise ValueError("invalid types format") + return tuple(parsed) + except json.JSONDecodeError as e: + logger.error("malformed types JSON: %s", value) + raise ValueError("malformed types JSON") from e + def parse_pokemon_types(value: Any) -> Any: """Helper function to parse the types JSON string. @@ -19,13 +47,7 @@ def parse_pokemon_types(value: Any) -> Any: ValueError: If the string is not valid JSON or not a list. """ if isinstance(value, str): - try: - parsed = json.loads(value) - if not isinstance(parsed, list): - raise ValueError("invalid types format") - return parsed - except json.JSONDecodeError as e: - raise ValueError("malformed types JSON") from e + return list(_parse_types_json(value)) return value