-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathquery_state.py
More file actions
85 lines (67 loc) · 2.68 KB
/
query_state.py
File metadata and controls
85 lines (67 loc) · 2.68 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
from typing import Any
from mpt_api_client.rql import RQLQuery
class QueryState:
"""Stores and manages API query state for filtering, selecting, and ordering data.
This class maintains the current state of query parameters (filter, order_by, select)
and provides functionality to build query strings from that state. It's responsible
for both storing query configuration and constructing the appropriate query parameters
that modify the behavior and shape of data returned by the API.
"""
def __init__(
self,
rql: RQLQuery | None = None,
order_by: list[str] | None = None,
select: list[str] | None = None,
*,
render: bool = False,
) -> None:
"""Initialize the query state with optional filter, ordering, and selection criteria.
Args:
rql: RQL query for filtering data.
order_by: List of fields to order by (prefix with '-' for descending).
select: List of fields to select in the response.
render: Whether to include the render() parameter in the query string.
"""
self._filter = rql
self._order_by = order_by
self._select = select
self._render = render
@property
def filter(self) -> RQLQuery | None:
"""Get the current filter query."""
return self._filter
@property
def order_by(self) -> list[str] | None:
"""Get the current order by fields."""
return self._order_by
@property
def select(self) -> list[str] | None:
"""Get the current select fields."""
return self._select
@property
def render(self) -> bool:
"""Get the current render state."""
return self._render
def build(self, query_params: dict[str, Any] | None = None) -> str:
"""Build a query string from the current state and additional parameters.
Args:
query_params: Additional query parameters to include in the query string.
Returns:
Complete query string with all parameters, or empty string if no parameters.
"""
query_params = query_params or {}
if self._order_by:
query_params.update({"order": ",".join(self._order_by)})
if self._select:
query_params.update({"select": ",".join(self._select)})
query_parts = [
f"{param_key}={param_value}" for param_key, param_value in query_params.items()
]
if self._filter:
query_parts.append(str(self._filter))
if self._render:
query_parts.append("render()")
if query_parts:
query = "&".join(query_parts)
return f"{query}"
return ""