|
| 1 | +from collections.abc import AsyncIterator |
| 2 | +from urllib.parse import urljoin |
| 3 | + |
| 4 | +import httpx |
| 5 | + |
| 6 | +from mpt_api_client.http.async_client import AsyncHTTPClient |
| 7 | +from mpt_api_client.http.base_service import ServiceBase |
| 8 | +from mpt_api_client.models import Collection, ResourceData |
| 9 | +from mpt_api_client.models import Model as BaseModel |
| 10 | +from mpt_api_client.models.collection import ResourceList |
| 11 | + |
| 12 | + |
| 13 | +class AsyncService[Model: BaseModel](ServiceBase[AsyncHTTPClient, Model]): # noqa: WPS214 |
| 14 | + """Immutable Service for RESTful resource collections. |
| 15 | +
|
| 16 | + Examples: |
| 17 | + active_orders_cc = order_collection.filter(RQLQuery(status="active")) |
| 18 | + active_orders = active_orders_cc.order_by("created").iterate() |
| 19 | + product_active_orders = active_orders_cc.filter(RQLQuery(product__id="PRD-1")).iterate() |
| 20 | +
|
| 21 | + new_order = order_collection.create(order_data) |
| 22 | +
|
| 23 | + """ |
| 24 | + |
| 25 | + async def fetch_page(self, limit: int = 100, offset: int = 0) -> Collection[Model]: |
| 26 | + """Fetch one page of resources.""" |
| 27 | + response = await self._fetch_page_as_response(limit=limit, offset=offset) |
| 28 | + return self._create_collection(response) |
| 29 | + |
| 30 | + async def fetch_one(self) -> Model: |
| 31 | + """Fetch one resource, expect exactly one result. |
| 32 | +
|
| 33 | + Returns: |
| 34 | + One resource. |
| 35 | +
|
| 36 | + Raises: |
| 37 | + ValueError: If the total matching records are not exactly one. |
| 38 | + """ |
| 39 | + response = await self._fetch_page_as_response(limit=1, offset=0) |
| 40 | + resource_list = self._create_collection(response) |
| 41 | + total_records = len(resource_list) |
| 42 | + if resource_list.meta: |
| 43 | + total_records = resource_list.meta.pagination.total |
| 44 | + if total_records == 0: |
| 45 | + raise ValueError("Expected one result, but got zero results") |
| 46 | + if total_records > 1: |
| 47 | + raise ValueError(f"Expected one result, but got {total_records} results") |
| 48 | + |
| 49 | + return resource_list[0] |
| 50 | + |
| 51 | + async def iterate(self, batch_size: int = 100) -> AsyncIterator[Model]: |
| 52 | + """Iterate over all resources, yielding GenericResource objects. |
| 53 | +
|
| 54 | + Args: |
| 55 | + batch_size: Number of resources to fetch per request |
| 56 | +
|
| 57 | + Returns: |
| 58 | + Iterator of resources. |
| 59 | + """ |
| 60 | + offset = 0 |
| 61 | + limit = batch_size # Default page size |
| 62 | + |
| 63 | + while True: |
| 64 | + response = await self._fetch_page_as_response(limit=limit, offset=offset) |
| 65 | + items_collection = self._create_collection(response) |
| 66 | + for resource in items_collection: |
| 67 | + yield resource |
| 68 | + |
| 69 | + if not items_collection.meta: |
| 70 | + break |
| 71 | + if not items_collection.meta.pagination.has_next(): |
| 72 | + break |
| 73 | + offset = items_collection.meta.pagination.next_offset() |
| 74 | + |
| 75 | + async def create(self, resource_data: ResourceData) -> Model: |
| 76 | + """Create a new resource using `POST /endpoint`. |
| 77 | +
|
| 78 | + Returns: |
| 79 | + New resource created. |
| 80 | + """ |
| 81 | + response = await self.http_client.post(self._endpoint, json=resource_data) |
| 82 | + response.raise_for_status() |
| 83 | + |
| 84 | + return self._model_class.from_response(response) |
| 85 | + |
| 86 | + async def get(self, resource_id: str) -> Model: |
| 87 | + """Fetch a specific resource using `GET /endpoint/{resource_id}`.""" |
| 88 | + return await self._resource_action(resource_id=resource_id) |
| 89 | + |
| 90 | + async def update(self, resource_id: str, resource_data: ResourceData) -> Model: |
| 91 | + """Update a resource using `PUT /endpoint/{resource_id}`.""" |
| 92 | + return await self._resource_action(resource_id, "PUT", json=resource_data) |
| 93 | + |
| 94 | + async def delete(self, resource_id: str) -> None: |
| 95 | + """Delete resource using `DELETE /endpoint/{resource_id}`.""" |
| 96 | + url = urljoin(f"{self._endpoint}/", resource_id) |
| 97 | + response = await self.http_client.delete(url) |
| 98 | + response.raise_for_status() |
| 99 | + |
| 100 | + async def _fetch_page_as_response(self, limit: int = 100, offset: int = 0) -> httpx.Response: |
| 101 | + """Fetch one page of resources. |
| 102 | +
|
| 103 | + Returns: |
| 104 | + httpx.Response object. |
| 105 | +
|
| 106 | + Raises: |
| 107 | + HTTPStatusError: if the response status code is not 200. |
| 108 | + """ |
| 109 | + pagination_params: dict[str, int] = {"limit": limit, "offset": offset} |
| 110 | + response = await self.http_client.get(self.build_url(pagination_params)) |
| 111 | + response.raise_for_status() |
| 112 | + |
| 113 | + return response |
| 114 | + |
| 115 | + async def _resource_do_request( |
| 116 | + self, |
| 117 | + resource_id: str, |
| 118 | + method: str = "GET", |
| 119 | + action: str | None = None, |
| 120 | + json: ResourceData | ResourceList | None = None, |
| 121 | + ) -> httpx.Response: |
| 122 | + """Perform an action on a specific resource using. |
| 123 | +
|
| 124 | + Request with action: `HTTP_METHOD /endpoint/{resource_id}/{action}`. |
| 125 | + Request without action: `HTTP_METHOD /endpoint/{resource_id}`. |
| 126 | +
|
| 127 | + Args: |
| 128 | + resource_id: The resource ID to operate on. |
| 129 | + method: The HTTP method to use. |
| 130 | + action: The action name to use. |
| 131 | + json: The updated resource data. |
| 132 | +
|
| 133 | + Raises: |
| 134 | + HTTPError: If the action fails. |
| 135 | + """ |
| 136 | + resource_url = urljoin(f"{self._endpoint}/", resource_id) |
| 137 | + url = urljoin(f"{resource_url}/", action) if action else resource_url |
| 138 | + response = await self.http_client.request(method, url, json=json) |
| 139 | + response.raise_for_status() |
| 140 | + return response |
| 141 | + |
| 142 | + async def _resource_action( |
| 143 | + self, |
| 144 | + resource_id: str, |
| 145 | + method: str = "GET", |
| 146 | + action: str | None = None, |
| 147 | + json: ResourceData | ResourceList | None = None, |
| 148 | + ) -> Model: |
| 149 | + """Perform an action on a specific resource using `HTTP_METHOD /endpoint/{resource_id}`.""" |
| 150 | + response = await self._resource_do_request(resource_id, method, action, json=json) |
| 151 | + return self._model_class.from_response(response) |
0 commit comments