|
| 1 | +""" |
| 2 | +Django implementation of the BatchDataResolver interface. |
| 3 | +This module provides a way to execute multiple database queries in a single request. |
| 4 | +""" |
| 5 | +from typing import Dict, List, Any, Optional, Union, Tuple |
| 6 | +import json |
| 7 | +from django.http import JsonResponse |
| 8 | +from django.views.decorators.http import require_POST |
| 9 | +from django.views.decorators.csrf import csrf_exempt |
| 10 | +from django.db.models import Q, Model |
| 11 | +from django.apps import apps |
| 12 | + |
| 13 | +# Type definitions to match the TypeScript interface |
| 14 | +NonNullFieldValue = Union[str, int, float, bool] |
| 15 | +BaseFieldValue = Optional[NonNullFieldValue] |
| 16 | +ResolvedEntityData = Dict[str, BaseFieldValue] |
| 17 | + |
| 18 | +class DataFilter: |
| 19 | + """Represents a filter condition on a field.""" |
| 20 | + |
| 21 | + def __init__(self, field: str, value: Union[NonNullFieldValue, List[NonNullFieldValue]], operator: str = "equals"): |
| 22 | + self.field = field |
| 23 | + self.value = value |
| 24 | + self.operator = operator |
| 25 | + |
| 26 | + def to_q(self) -> Q: |
| 27 | + """Convert the filter to a Django Q object.""" |
| 28 | + if self.operator == "in": |
| 29 | + return Q(**{f"{self.field}__in": self.value}) |
| 30 | + # Default to equals |
| 31 | + return Q(**{self.field: self.value}) |
| 32 | + |
| 33 | + |
| 34 | +class DataQuery: |
| 35 | + """Represents a query on a specific model with filters.""" |
| 36 | + |
| 37 | + def __init__(self, model: str, filters: List[DataFilter]): |
| 38 | + self.model = model.replace("_", ".", 1) # Convert to Django model path |
| 39 | + self.filters = filters |
| 40 | + |
| 41 | + def get_model_class(self) -> Model: |
| 42 | + """Get the Django model class from the model name.""" |
| 43 | + try: |
| 44 | + return apps.get_model(self.model) |
| 45 | + except LookupError: |
| 46 | + raise ValueError(f"Model {self.model} not found") |
| 47 | + |
| 48 | + def execute(self, fields: List[str]) -> List[ResolvedEntityData]: |
| 49 | + """Execute the query and return the results.""" |
| 50 | + model_class = self.get_model_class() |
| 51 | + |
| 52 | + # Build the filter query |
| 53 | + query = Q() |
| 54 | + for filter_obj in self.filters: |
| 55 | + query &= filter_obj.to_q() |
| 56 | + |
| 57 | + # Execute the query and return the results |
| 58 | + queryset = model_class.objects.filter(query) |
| 59 | + # Convert to list of dictionaries with only the requested fields |
| 60 | + result = [] |
| 61 | + for instance in queryset: |
| 62 | + entity_data = {} |
| 63 | + for field in fields: |
| 64 | + try: |
| 65 | + value = getattr(instance, field) |
| 66 | + # Ensure the value is of a compatible type |
| 67 | + if value is not None and not isinstance(value, (str, int, float, bool)): |
| 68 | + value = str(value) |
| 69 | + entity_data[field] = value |
| 70 | + except AttributeError: |
| 71 | + entity_data[field] = None |
| 72 | + result.append(entity_data) |
| 73 | + |
| 74 | + return result |
| 75 | + |
| 76 | + |
| 77 | +class DataResolver: |
| 78 | + """Resolver for a single data query.""" |
| 79 | + |
| 80 | + @staticmethod |
| 81 | + def fetch(input_data: Dict[str, Any]) -> List[ResolvedEntityData]: |
| 82 | + """Fetch data based on the input query.""" |
| 83 | + query = DataQuery( |
| 84 | + model=input_data["query"]["model"], |
| 85 | + filters=[ |
| 86 | + DataFilter( |
| 87 | + field=filter_obj["field"], |
| 88 | + value=filter_obj["value"], |
| 89 | + operator=filter_obj.get("operator", "equals") |
| 90 | + ) |
| 91 | + for filter_obj in input_data["query"]["filter"] |
| 92 | + ] |
| 93 | + ) |
| 94 | + return query.execute(input_data["fields"]) |
| 95 | + |
| 96 | + |
| 97 | +class BatchDataResolver: |
| 98 | + """Resolver for multiple data queries in one batch.""" |
| 99 | + |
| 100 | + @staticmethod |
| 101 | + def fetchBatch(batch: Dict[str, Dict[str, Any]]) -> Dict[str, List[ResolvedEntityData]]: |
| 102 | + """Fetch multiple queries serially and return results keyed by query ID.""" |
| 103 | + results = {} |
| 104 | + for key, input_data in batch.items(): |
| 105 | + results[key] = DataResolver.fetch(input_data) |
| 106 | + return results |
| 107 | + |
| 108 | + |
| 109 | +@csrf_exempt |
| 110 | +@require_POST |
| 111 | +def batch_data_api(request): |
| 112 | + """API endpoint that handles batch data requests.""" |
| 113 | + try: |
| 114 | + # Parse the request body |
| 115 | + batch_data = json.loads(request.body) |
| 116 | + # Validate the input |
| 117 | + if not isinstance(batch_data, dict): |
| 118 | + return JsonResponse({"error": "Input must be a dictionary"}, status=400) |
| 119 | + # Execute the batch query |
| 120 | + results = BatchDataResolver.fetchBatch(batch_data) |
| 121 | + # Return the results |
| 122 | + return JsonResponse(results, safe=False) |
| 123 | + |
| 124 | + except json.JSONDecodeError: |
| 125 | + return JsonResponse({"error": "Invalid JSON"}, status=400) |
| 126 | + except Exception as e: |
| 127 | + return JsonResponse({"error": str(e)}, status=500) |
0 commit comments