Skip to content

Commit

Permalink
Use separate DjangoFilterExtension to update URLViewFilter fields
Browse files Browse the repository at this point in the history
  • Loading branch information
SonnyBA committed Nov 25, 2024
1 parent 3a0255a commit fce3a5a
Showing 1 changed file with 28 additions and 16 deletions.
44 changes: 28 additions & 16 deletions src/openklant/utils/query.py
Original file line number Diff line number Diff line change
@@ -1,30 +1,42 @@
# SPDX-License-Identifier: EUPL-1.2
# Copyright (C) 2024 Dimpact
from drf_spectacular.contrib.django_filters import DjangoFilterExtension
from drf_spectacular.utils import OpenApiParameter
from vng_api_common.utils import underscore_to_camel

from openklant.components.utils.filters import URLViewFilter


class CamelizeFilterExtension(DjangoFilterExtension):
priority = 1

def get_schema_operation_parameters(self, auto_schema, *args, **kwargs):
"""
camelize query parameters
"""
parameters = super().get_schema_operation_parameters(
auto_schema, *args, **kwargs
def resolve_filter_field(
self, auto_schema, model, filterset_class, field_name, filter_field
) -> list[dict]:
results = super().resolve_filter_field(
auto_schema, model, filterset_class, field_name, filter_field
)

for parameter in parameters:
parameter["name"] = underscore_to_camel(parameter["name"])
for result in results:
result["name"] = underscore_to_camel(result["name"])

return results


class UUIDURLFilterExtension(CamelizeFilterExtension):
priority = 2

def resolve_filter_field(
self, auto_schema, model, filterset_class, field_name, filter_field
) -> list[dict]:
results = super().resolve_filter_field(
auto_schema, model, filterset_class, field_name, filter_field
)

# reshape url fields which has incorrect field format
is_query = parameter["in"] == OpenApiParameter.QUERY
is_string = parameter["schema"]["type"] == "string"
is_url_field = parameter["name"].endswith("__url")
if not isinstance(filter_field, URLViewFilter):
return results

if all((is_query, is_string, is_url_field)):
parameter["schema"] = {"type": "string", "format": "uri"}
for result in results:
schema = result.setdefault("schema", {})
schema.update({"type": "string", "format": "uri"})

return parameters
return results

0 comments on commit fce3a5a

Please sign in to comment.