diff --git a/src/app/schemas/pokemon.py b/src/app/schemas/pokemon.py index 7111dad..b31197c 100644 --- a/src/app/schemas/pokemon.py +++ b/src/app/schemas/pokemon.py @@ -1,10 +1,36 @@ """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 +def _parse_types_json(value: str) -> tuple[str, ...]: + """Private helper to parse and cache JSON types string into an immutable tuple. + + Args: + value: The JSON string to parse. + + Returns: + A 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): + raise ValueError("invalid types format") + return tuple(parsed) + except json.JSONDecodeError as e: + raise ValueError("malformed types JSON") from e + def parse_pokemon_types(value: Any) -> Any: """Helper function to parse the types JSON string. @@ -19,13 +45,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