Skip to content

Commit d1bd3f8

Browse files
committed
better variable/function names
1 parent ecb96e6 commit d1bd3f8

File tree

4 files changed

+62
-52
lines changed

4 files changed

+62
-52
lines changed

src/django_idom/hooks.py

Lines changed: 35 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,14 @@
1414
from idom.backend.types import Location
1515
from idom.core.hooks import Context, create_context, use_context, use_effect, use_state
1616

17-
from django_idom.types import IdomWebsocket, Mutation, OrmFetch, Query, _Params, _Result
17+
from django_idom.types import (
18+
IdomWebsocket,
19+
Mutation,
20+
QueryOptions,
21+
Query,
22+
_Params,
23+
_Result,
24+
)
1825
from django_idom.utils import _generate_obj_name
1926

2027

@@ -68,7 +75,7 @@ def use_websocket() -> IdomWebsocket:
6875

6976

7077
def use_query(
71-
query: Callable[_Params, _Result | None] | OrmFetch,
78+
query: Callable[_Params, _Result | None] | QueryOptions,
7279
*args: _Params.args,
7380
**kwargs: _Params.kwargs,
7481
) -> Query[_Result | None]:
@@ -88,7 +95,9 @@ def use_query(
8895
data, set_data = use_state(cast(Union[_Result, None], None))
8996
loading, set_loading = use_state(True)
9097
error, set_error = use_state(cast(Union[Exception, None], None))
91-
fetch_cls = query if isinstance(query, OrmFetch) else OrmFetch(query)
98+
query_options = (
99+
query if isinstance(query, QueryOptions) else QueryOptions(func=query)
100+
)
92101

93102
@use_callback
94103
def refetch() -> None:
@@ -100,8 +109,8 @@ def refetch() -> None:
100109
def add_refetch_callback() -> Callable[[], None]:
101110
# By tracking callbacks globally, any usage of the query function will be re-run
102111
# if the user has told a mutation to refetch it.
103-
_REFETCH_CALLBACKS[fetch_cls.func].add(refetch)
104-
return lambda: _REFETCH_CALLBACKS[fetch_cls.func].remove(refetch)
112+
_REFETCH_CALLBACKS[query_options.func].add(refetch)
113+
return lambda: _REFETCH_CALLBACKS[query_options.func].remove(refetch)
105114

106115
@use_effect(dependencies=None)
107116
@database_sync_to_async
@@ -111,15 +120,15 @@ def execute_query() -> None:
111120

112121
try:
113122
# Run the initial query
114-
fetch_cls.data = fetch_cls.func(*args, **kwargs)
123+
query_options._data = query_options.func(*args, **kwargs)
115124

116-
# Use a custom evaluator, if provided
117-
if fetch_cls.evaluator:
118-
fetch_cls.evaluator(fetch_cls)
125+
# Use a custom postprocessor, if provided
126+
if query_options.postprocessor:
127+
query_options.postprocessor(query_options)
119128

120-
# Evaluate lazy Django fields
129+
# Use the default postprocessor
121130
else:
122-
_evaluate_django_query(fetch_cls)
131+
_postprocess_django_query(query_options)
123132
except Exception as e:
124133
set_data(None)
125134
set_loading(False)
@@ -131,7 +140,7 @@ def execute_query() -> None:
131140
finally:
132141
set_should_execute(False)
133142

134-
set_data(fetch_cls.data)
143+
set_data(query_options._data)
135144
set_loading(False)
136145
set_error(None)
137146

@@ -191,21 +200,21 @@ def reset() -> None:
191200
return Mutation(call, loading, error, reset)
192201

193202

194-
def _evaluate_django_query(fetch_cls: OrmFetch) -> None:
203+
def _postprocess_django_query(fetch_cls: QueryOptions) -> None:
195204
"""Recursively fetch all fields within a `Model` or `QuerySet` to ensure they are not performed lazily.
196205
197206
Some behaviors can be modified through `OrmFetch` attributes."""
198-
data = fetch_cls.data
207+
data = fetch_cls._data
199208

200209
# `QuerySet`, which is effectively a list of `Model` instances
201210
# https://github.com/typeddjango/django-stubs/issues/704
202211
if isinstance(data, QuerySet): # type: ignore[misc]
203212
for model in data:
204-
_evaluate_django_query(
205-
OrmFetch(
213+
_postprocess_django_query(
214+
QueryOptions(
206215
func=fetch_cls.func,
207-
data=model,
208-
options=fetch_cls.options,
216+
_data=model,
217+
postprocessor_options=fetch_cls.postprocessor_options,
209218
)
210219
)
211220

@@ -219,20 +228,20 @@ def _evaluate_django_query(fetch_cls: OrmFetch) -> None:
219228
getattr(data, field.name)
220229

221230
if (
222-
fetch_cls.options.get("many_to_one", None)
231+
fetch_cls.postprocessor_options.get("many_to_one", None)
223232
and type(field) == ManyToOneRel
224233
):
225234
prefetch_fields.append(f"{field.name}_set")
226235

227-
elif fetch_cls.options.get("many_to_many", None) and isinstance(
228-
field, ManyToManyField
229-
):
236+
elif fetch_cls.postprocessor_options.get(
237+
"many_to_many", None
238+
) and isinstance(field, ManyToManyField):
230239
prefetch_fields.append(field.name)
231-
_evaluate_django_query(
232-
OrmFetch(
240+
_postprocess_django_query(
241+
QueryOptions(
233242
func=fetch_cls.func,
234-
data=getattr(data, field.name).get_queryset(),
235-
options=fetch_cls.options,
243+
_data=getattr(data, field.name).get_queryset(),
244+
postprocessor_options=fetch_cls.postprocessor_options,
236245
)
237246
)
238247

src/django_idom/types.py

Lines changed: 11 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -53,21 +53,22 @@ class ViewComponentIframe:
5353
kwargs: dict
5454

5555

56-
@dataclass
57-
class OrmFetch:
58-
"""A Django ORM fetch."""
56+
@dataclass(kw_only=True)
57+
class QueryOptions:
58+
"""A Django ORM query function, alongside some configuration values."""
5959

6060
func: Callable
61-
"""Callable that fetches ORM objects."""
61+
"""Callable that fetches ORM object(s)."""
6262

63-
data: Any | None = None
64-
"""The results of a fetch operation."""
63+
_data: Any = None
64+
"""The results of a fetch operation.
65+
This is only intended to be set automatically by the `use_query` hook."""
6566

66-
options: dict[str, Any] = field(
67+
postprocessor_options: dict[str, Any] = field(
6768
default_factory=lambda: {"many_to_many": True, "many_to_one": True}
6869
)
69-
"""Configuration values usable by the `fetch_handler`."""
70+
"""Configuration values usable by the `postprocessor`."""
7071

71-
evaluator: Callable[[OrmFetch], None] | None = None
72-
"""A post-processing callable that can read/modify the `OrmFetch` object. If unset, the default fetch
72+
postprocessor: Callable[[QueryOptions], None] | None = None
73+
"""A post processing callable that can read/modify the `OrmFetch` object. If unset, the default fetch
7374
handler is used to prevent lazy loading of Django fields."""

src/django_idom/utils.py

Lines changed: 14 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@
1616
from django.views import View
1717

1818
from django_idom.config import IDOM_REGISTERED_COMPONENTS
19-
from django_idom.types import OrmFetch, _Params, _Result
19+
from django_idom.types import QueryOptions, _Params, _Result
2020

2121

2222
_logger = logging.getLogger(__name__)
@@ -203,35 +203,35 @@ def _generate_obj_name(object: Any) -> str | None:
203203

204204

205205
@overload
206-
def fetch_options(
206+
def query_options(
207207
query_func: None = ...,
208-
evaluator: Callable[[OrmFetch], None] | None = None,
208+
evaluator: Callable[[QueryOptions], None] | None = None,
209209
**options,
210-
) -> Callable[[Callable[_Params, _Result]], OrmFetch]:
210+
) -> Callable[[Callable[_Params, _Result]], QueryOptions]:
211211
...
212212

213213

214214
@overload
215-
def fetch_options(
215+
def query_options(
216216
query_func: Callable[_Params, _Result],
217-
evaluator: Callable[[OrmFetch], None] | None = None,
217+
evaluator: Callable[[QueryOptions], None] | None = None,
218218
**options,
219-
) -> OrmFetch:
219+
) -> QueryOptions:
220220
...
221221

222222

223-
def fetch_options(
223+
def query_options(
224224
query_func: Callable[_Params, _Result] | None = None,
225-
evaluator: Callable[[OrmFetch], None] | None = None,
225+
evaluator: Callable[[QueryOptions], None] | None = None,
226226
**options,
227-
) -> OrmFetch | Callable[[Callable[_Params, _Result]], OrmFetch]:
227+
) -> QueryOptions | Callable[[Callable[_Params, _Result]], QueryOptions]:
228228
def decorator(query_func: Callable[_Params, _Result]):
229229
if not query_func:
230-
raise ValueError("A query function must be provided to `fetch_options`")
230+
raise ValueError("A query function must be provided to `query_options`")
231231

232-
fetch_options = OrmFetch(func=query_func, evaluator=evaluator)
232+
query_options = QueryOptions(func=query_func, postprocessor=evaluator)
233233
if options:
234-
fetch_options.options.update(options)
235-
return fetch_options
234+
query_options.postprocessor_options.update(options)
235+
return query_options
236236

237237
return decorator(query_func) if query_func else decorator

tests/test_app/components.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
import django_idom
99
from django_idom.components import view_to_component
1010
from django_idom.hooks import use_mutation, use_query
11-
from django_idom.utils import fetch_options
11+
from django_idom.utils import query_options
1212

1313
from . import views
1414

@@ -207,7 +207,7 @@ def relational_query():
207207
)
208208

209209

210-
@fetch_options(many_to_many=False, many_to_one=False)
210+
@query_options(many_to_many=False, many_to_one=False)
211211
def get_relational_parent_query_fail():
212212
return RelationalParent.objects.first() or create_relational_parent()
213213

0 commit comments

Comments
 (0)