-
Notifications
You must be signed in to change notification settings - Fork 3
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Use separate
DjangoFilterExtension
to update URLViewFilter
fields
- Loading branch information
Showing
1 changed file
with
28 additions
and
16 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |