|
| 1 | +from dataclasses import dataclass |
| 2 | +from typing import ( |
| 3 | + TYPE_CHECKING, |
| 4 | + Any, |
| 5 | + Dict, |
| 6 | + List, |
| 7 | + Literal, |
| 8 | + Optional, |
| 9 | + Type, |
| 10 | + Union, |
| 11 | +) |
| 12 | + |
| 13 | +from fastapi import APIRouter, Request |
| 14 | + |
| 15 | +from fastapi_jsonapi import RoutersJSONAPI |
| 16 | +from fastapi_jsonapi.atomic.schemas import ( |
| 17 | + AtomicOperationRequest, |
| 18 | + AtomicResultResponse, |
| 19 | + OperationItemInSchema, |
| 20 | + OperationRelationshipSchema, |
| 21 | +) |
| 22 | +from fastapi_jsonapi.utils.dependency_helper import DependencyHelper |
| 23 | +from fastapi_jsonapi.views.utils import HTTPMethodConfig |
| 24 | +from fastapi_jsonapi.views.view_base import ViewBase |
| 25 | + |
| 26 | +if TYPE_CHECKING: |
| 27 | + from fastapi_jsonapi.data_layers.base import BaseDataLayer |
| 28 | + from fastapi_jsonapi.views.list_view import ListViewBase |
| 29 | + |
| 30 | + |
| 31 | +@dataclass |
| 32 | +class PreparedOperation: |
| 33 | + action: Literal["add", "update", "remove"] |
| 34 | + data_layer: "BaseDataLayer" |
| 35 | + view: "ViewBase" |
| 36 | + jsonapi: RoutersJSONAPI |
| 37 | + data: Union[ |
| 38 | + # from biggest to smallest! |
| 39 | + # any object creation |
| 40 | + OperationItemInSchema, |
| 41 | + # to-many relationship |
| 42 | + List[OperationRelationshipSchema], |
| 43 | + # to-one relationship |
| 44 | + OperationRelationshipSchema, |
| 45 | + # not required |
| 46 | + None, |
| 47 | + ] = None |
| 48 | + |
| 49 | + |
| 50 | +class AtomicOperations: |
| 51 | + def __init__( |
| 52 | + self, |
| 53 | + url_path: str = "/operations", |
| 54 | + router: Optional[APIRouter] = None, |
| 55 | + ): |
| 56 | + self.router = router or APIRouter(tags=["Atomic Operations"]) |
| 57 | + self.url_path = url_path |
| 58 | + self._register_view() |
| 59 | + |
| 60 | + async def handle_view_dependencies( |
| 61 | + self, |
| 62 | + request: Request, |
| 63 | + jsonapi: RoutersJSONAPI, |
| 64 | + ) -> Dict[str, Any]: |
| 65 | + method_config: HTTPMethodConfig = jsonapi.get_method_config_for_create() |
| 66 | + |
| 67 | + def handle_dependencies(**dep_kwargs): |
| 68 | + return dep_kwargs |
| 69 | + |
| 70 | + handle_dependencies.__signature__ = jsonapi.prepare_dependencies_handler_signature( |
| 71 | + custom_handler=handle_dependencies, |
| 72 | + method_config=method_config, |
| 73 | + ) |
| 74 | + |
| 75 | + dependencies_result: Dict[str, Any] = await DependencyHelper(request=request).run(handle_dependencies) |
| 76 | + return dependencies_result |
| 77 | + |
| 78 | + async def view_atomic( |
| 79 | + self, |
| 80 | + request: Request, |
| 81 | + operations_request: AtomicOperationRequest, |
| 82 | + ): |
| 83 | + prepared_operations: List[PreparedOperation] = [] |
| 84 | + |
| 85 | + for operation in operations_request.operations: |
| 86 | + jsonapi = RoutersJSONAPI.all_jsonapi_routers[operation.data.type] |
| 87 | + view_cls: Type["ViewBase"] = jsonapi.detail_view_resource |
| 88 | + if operation.op == "add": |
| 89 | + view_cls = jsonapi.list_view_resource |
| 90 | + view = view_cls(request=request, jsonapi=jsonapi) |
| 91 | + dependencies_result: Dict[str, Any] = await self.handle_view_dependencies( |
| 92 | + request=request, |
| 93 | + jsonapi=jsonapi, |
| 94 | + ) |
| 95 | + dl: "BaseDataLayer" = await view.get_data_layer(dependencies_result) |
| 96 | + |
| 97 | + one_operation = PreparedOperation( |
| 98 | + action=operation.op, |
| 99 | + data_layer=dl, |
| 100 | + view=view, |
| 101 | + jsonapi=jsonapi, |
| 102 | + data=operation.data, |
| 103 | + ) |
| 104 | + prepared_operations.append(one_operation) |
| 105 | + |
| 106 | + results = [] |
| 107 | + |
| 108 | + for operation in prepared_operations: |
| 109 | + dl = operation.data_layer |
| 110 | + if operation.action == "add": |
| 111 | + data = operation.jsonapi.schema_in_post(data=operation.data) |
| 112 | + created_object = await dl.create_object( |
| 113 | + data_create=data.data, |
| 114 | + view_kwargs={}, |
| 115 | + ) |
| 116 | + # assert isinstance(operation.view, ListViewBase) |
| 117 | + view: "ListViewBase" = operation.view |
| 118 | + response = await view.response_for_created_object( |
| 119 | + dl=operation.data_layer, |
| 120 | + created_object=created_object, |
| 121 | + ) |
| 122 | + results.append({"data": response.data}) |
| 123 | + elif operation.action == "update": |
| 124 | + # TODO |
| 125 | + data = operation.jsonapi.schema_in_patch(data=operation.data) |
| 126 | + elif operation.action == "remove": |
| 127 | + pass |
| 128 | + else: |
| 129 | + msg = f"unknown action {operation.action!r}" |
| 130 | + raise ValueError(msg) |
| 131 | + |
| 132 | + return {"atomic:results": results} |
| 133 | + |
| 134 | + def _register_view(self): |
| 135 | + self.router.add_api_route( |
| 136 | + path=self.url_path, |
| 137 | + endpoint=self.view_atomic, |
| 138 | + response_model=AtomicResultResponse, |
| 139 | + methods=["Post"], |
| 140 | + summary="Atomic operations", |
| 141 | + description="""[https://jsonapi.org/ext/atomic/](https://jsonapi.org/ext/atomic/)""", |
| 142 | + ) |
0 commit comments