Skip to content

Commit

Permalink
Respect custom fields style (#38)
Browse files Browse the repository at this point in the history
* Respect custom fields style

* fix types
  • Loading branch information
Olegt0rr authored Apr 22, 2024
1 parent 8378bd2 commit 1eccaa9
Showing 1 changed file with 26 additions and 10 deletions.
36 changes: 26 additions & 10 deletions yatracker/tracker/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,13 +76,14 @@ def _prepare_payload(
"""Remove empty fields from payload."""
payload = payload.copy()
exclude = exclude or []
kwargs = payload.pop("kwargs", None)

kwargs: dict | None = payload.pop("kwargs", None)
if kwargs:
if type_ is not None:
kwargs = _replace_custom_fields(kwargs, type_)
payload.update(kwargs)

if type_ is not None:
return _rename_and_clear(type_, payload, exclude)

return {
camel_case(k): _convert_value(v)
for k, v in payload.items()
Expand Down Expand Up @@ -144,12 +145,27 @@ def _convert_value(obj: Any) -> Any: # noqa: ANN401
return obj


def _replace_custom_fields(kwargs: dict[str, Any], type_: type[B]) -> dict[str, Any]:
def _rename_and_clear(
type_: type[B],
payload: dict[str, Any],
exclude: Collection[str],
) -> dict[str, Any]:
"""Replace kwarg key with original field name."""
new_kwargs: dict[str, Any] = {}
for key, value in kwargs.items():
if not hasattr(type_, key):
renamed: dict[str, Any] = {}
exclude = {"self", "cls", *exclude}

for name, encode_name in zip(
type_.__struct_fields__,
type_.__struct_encode_fields__, # type: ignore[attr-defined]
strict=False,
):
if name not in payload or name in exclude or name.startswith("_"):
continue

value = _convert_value(payload[name])
if value is None:
continue
field = getattr(type_, key)
new_kwargs[field.name] = value
return new_kwargs

renamed[encode_name] = value

return renamed

0 comments on commit 1eccaa9

Please sign in to comment.