1"""Filters for Battle.net search endpoints.
2
3Search methods take ``filters``, a mapping from a document field to a value::
4
5 client.items.search(
6 filters={
7 "item_class.id": 2, # equals
8 "quality.type": ["EPIC", "LEGENDARY"], # any of
9 "required_level": Range(50, 60), # 50 <= level <= 60
10 "inventory_type.type": Not("SHIELD"), # not equal
11 },
12 order_by=["level:desc", "id"],
13 )
14
15Field names follow the search document, with dots for nesting. Localized fields take a locale suffix, as in
16``name.en_US``.
17"""
18
19from collections.abc import Mapping, Sequence
20from dataclasses import dataclass
21from typing import Final
22
23__all__ = ["MAX_PAGE_SIZE", "FilterValue", "Not", "Range", "encode_search"]
24
25MAX_PAGE_SIZE: Final = 1000
26"""The largest ``page_size`` Battle.net accepts, and also the most results one query returns."""
27
28type Scalar = str | int
29
30
31@dataclass(frozen=True, slots=True)
[docs]
32class Range:
33 """Match a numeric field between two bounds; leave one out for an open range.
34
35 Attributes:
36 min: The lower bound, or ``None`` for no lower bound.
37 max: The upper bound, or ``None`` for no upper bound.
38 inclusive: Whether the bounds themselves match.
39 """
40
41 min: int | None = None
42 max: int | None = None
43 inclusive: bool = True
44
45 def __post_init__(self) -> None:
46 if self.min is None and self.max is None:
47 msg = "Range needs at least one bound"
48 raise ValueError(msg)
49
[docs]
50 def encode(self) -> str:
51 """Render Blizzard's range syntax, such as ``[50,60]`` or ``(,77)``."""
52 low = "" if self.min is None else str(self.min)
53 high = "" if self.max is None else str(self.max)
54 opening, closing = ("[", "]") if self.inclusive else ("(", ")")
55 return f"{opening}{low},{high}{closing}"
56
57
58@dataclass(frozen=True, slots=True)
[docs]
59class Not:
60 """Match documents whose field is not this value.
61
62 Attributes:
63 value: The value to exclude.
64 """
65
66 value: Scalar
67
68
69type FilterValue = Scalar | bool | Range | Not | Sequence[Scalar]
70"""A filter value: equals for a scalar, any-of for a sequence, plus :class:`Range` and :class:`Not`."""
71
72
73def _scalar(value: Scalar) -> str:
74 if isinstance(value, bool):
75 return "true" if value else "false"
76 return str(value)
77
78
[docs]
79def encode_search(
80 filters: Mapping[str, FilterValue] | None,
81 *,
82 order_by: str | Sequence[str] | None,
83 page: int,
84 page_size: int,
85) -> dict[str, str | int]:
86 """Turn search arguments into query parameters.
87
88 Raises:
89 ValueError: ``page`` or ``page_size`` is out of range, or a sequence filter is empty.
90 """
91 if page < 1:
92 msg = f"page must be at least 1, got {page}"
93 raise ValueError(msg)
94 if not 1 <= page_size <= MAX_PAGE_SIZE:
95 msg = f"page_size must be between 1 and {MAX_PAGE_SIZE}, got {page_size}"
96 raise ValueError(msg)
97 params: dict[str, str | int] = {"_page": page, "_pageSize": page_size}
98 if order_by:
99 params["orderby"] = order_by if isinstance(order_by, str) else ",".join(order_by)
100 for field, value in (filters or {}).items():
101 match value:
102 case Range():
103 params[field] = value.encode()
104 case Not():
105 params[f"{field}!"] = _scalar(value.value)
106 case str() | int():
107 params[field] = _scalar(value)
108 case _:
109 if not value:
110 msg = f"filter {field!r} has an empty list of values"
111 raise ValueError(msg)
112 params[field] = "||".join(_scalar(item) for item in value)
113 return params