Skip to content
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 27 additions & 7 deletions src/app/schemas/pokemon.py
Original file line number Diff line number Diff line change
@@ -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.
Expand All @@ -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


Expand Down
Loading