|
5 | 5 | """ |
6 | 6 |
|
7 | 7 | import types |
8 | | -from typing import List, Optional, Tuple, Type |
| 8 | +from typing import Dict, List, Optional, Tuple, Type |
9 | 9 |
|
10 | 10 | from fastapi_jsonapi.data_typing import TypeModel, TypeSchema |
11 | 11 | from fastapi_jsonapi.querystring import QueryStringManager |
12 | 12 | from fastapi_jsonapi.schema import BaseJSONAPIItemInSchema |
| 13 | +from fastapi_jsonapi.schema_builder import FieldConfig, TransferSaveWrapper |
13 | 14 |
|
14 | 15 |
|
15 | 16 | class BaseDataLayer: |
@@ -75,6 +76,38 @@ async def atomic_start(self, previous_dl: Optional["BaseDataLayer"] = None): |
75 | 76 | async def atomic_end(self, success: bool = True): |
76 | 77 | raise NotImplementedError |
77 | 78 |
|
| 79 | + def _unwrap_field_config(self, extra: Dict): |
| 80 | + field_config_wrapper: Optional[TransferSaveWrapper] = extra.get("field_config") |
| 81 | + |
| 82 | + if field_config_wrapper: |
| 83 | + return field_config_wrapper.get_field_config() |
| 84 | + |
| 85 | + return FieldConfig() |
| 86 | + |
| 87 | + def _apply_client_generated_id( |
| 88 | + self, |
| 89 | + data_create: BaseJSONAPIItemInSchema, |
| 90 | + model_kwargs: dict, |
| 91 | + ): |
| 92 | + """ |
| 93 | + :param data_create: the data validated by pydantic. |
| 94 | + :param model_kwargs: the data validated by pydantic. |
| 95 | + """ |
| 96 | + if data_create.id is None: |
| 97 | + return model_kwargs |
| 98 | + |
| 99 | + extra = data_create.__fields__["id"].field_info.extra |
| 100 | + if extra.get("client_can_set_id"): |
| 101 | + id_value = data_create.id |
| 102 | + field_config = self._unwrap_field_config(extra) |
| 103 | + |
| 104 | + if field_config.cast_type: |
| 105 | + id_value = field_config.cast_type(id_value) |
| 106 | + |
| 107 | + model_kwargs["id"] = id_value |
| 108 | + |
| 109 | + return model_kwargs |
| 110 | + |
78 | 111 | async def create_object(self, data_create: BaseJSONAPIItemInSchema, view_kwargs: dict) -> TypeModel: |
79 | 112 | """ |
80 | 113 | Create an object |
|
0 commit comments