|
1 | 1 | import json |
| 2 | +from collections.abc import AsyncIterator, Iterator |
2 | 3 | from typing import Self |
3 | 4 | from urllib.parse import urljoin |
4 | 5 |
|
5 | 6 | from mpt_api_client.http.query_state import QueryState |
6 | 7 | from mpt_api_client.http.types import FileTypes, Response |
7 | | -from mpt_api_client.models import FileModel, ResourceData |
| 8 | +from mpt_api_client.models import Collection, FileModel, ResourceData |
| 9 | +from mpt_api_client.models import Model as BaseModel |
8 | 10 | from mpt_api_client.rql import RQLQuery |
9 | 11 |
|
10 | 12 |
|
@@ -301,3 +303,162 @@ def _create_new_instance( |
301 | 303 | query_state=query_state, |
302 | 304 | endpoint_params=self.endpoint_params, # type: ignore[attr-defined] |
303 | 305 | ) |
| 306 | + |
| 307 | + |
| 308 | +class CollectionMixin[Model: BaseModel](QueryableMixin): |
| 309 | + """Mixin providing collection functionality.""" |
| 310 | + |
| 311 | + def fetch_page(self, limit: int = 100, offset: int = 0) -> Collection[Model]: |
| 312 | + """Fetch one page of resources. |
| 313 | +
|
| 314 | + Returns: |
| 315 | + Collection of resources. |
| 316 | + """ |
| 317 | + response = self._fetch_page_as_response(limit=limit, offset=offset) |
| 318 | + return self.make_collection(response) # type: ignore[attr-defined, no-any-return] |
| 319 | + |
| 320 | + def fetch_one(self) -> Model: |
| 321 | + """Fetch one resource, expect exactly one result. |
| 322 | +
|
| 323 | + Returns: |
| 324 | + One resource. |
| 325 | +
|
| 326 | + Raises: |
| 327 | + ValueError: If the total matching records are not exactly one. |
| 328 | + """ |
| 329 | + response = self._fetch_page_as_response(limit=1, offset=0) |
| 330 | + resource_list = self.make_collection(response) # type: ignore[attr-defined] |
| 331 | + total_records = len(resource_list) |
| 332 | + if resource_list.meta: |
| 333 | + total_records = resource_list.meta.pagination.total |
| 334 | + if total_records == 0: |
| 335 | + raise ValueError("Expected one result, but got zero results") |
| 336 | + if total_records > 1: |
| 337 | + raise ValueError(f"Expected one result, but got {total_records} results") |
| 338 | + |
| 339 | + return resource_list[0] # type: ignore[no-any-return] |
| 340 | + |
| 341 | + def iterate(self, batch_size: int = 100) -> Iterator[Model]: |
| 342 | + """Iterate over all resources, yielding GenericResource objects. |
| 343 | +
|
| 344 | + Args: |
| 345 | + batch_size: Number of resources to fetch per request |
| 346 | +
|
| 347 | + Returns: |
| 348 | + Iterator of resources. |
| 349 | + """ |
| 350 | + offset = 0 |
| 351 | + limit = batch_size # Default page size |
| 352 | + |
| 353 | + while True: |
| 354 | + response = self._fetch_page_as_response(limit=limit, offset=offset) |
| 355 | + items_collection = self.make_collection(response) # type: ignore[attr-defined] |
| 356 | + yield from items_collection |
| 357 | + |
| 358 | + if not items_collection.meta: |
| 359 | + break |
| 360 | + if not items_collection.meta.pagination.has_next(): |
| 361 | + break |
| 362 | + offset = items_collection.meta.pagination.next_offset() |
| 363 | + |
| 364 | + def _fetch_page_as_response(self, limit: int = 100, offset: int = 0) -> Response: |
| 365 | + """Fetch one page of resources. |
| 366 | +
|
| 367 | + Returns: |
| 368 | + Response object. |
| 369 | +
|
| 370 | + Raises: |
| 371 | + HTTPStatusError: if the response status code is not 200. |
| 372 | + """ |
| 373 | + pagination_params: dict[str, int] = {"limit": limit, "offset": offset} |
| 374 | + return self.http_client.request("get", self.build_path(pagination_params)) # type: ignore[attr-defined, no-any-return] |
| 375 | + |
| 376 | + |
| 377 | +class AsyncCollectionMixin[Model: BaseModel](QueryableMixin): |
| 378 | + """Async mixin providing collection functionality.""" |
| 379 | + |
| 380 | + async def fetch_page(self, limit: int = 100, offset: int = 0) -> Collection[Model]: |
| 381 | + """Fetch one page of resources. |
| 382 | +
|
| 383 | + Returns: |
| 384 | + Collection of resources. |
| 385 | + """ |
| 386 | + response = await self._fetch_page_as_response(limit=limit, offset=offset) |
| 387 | + return self.make_collection(response) # type: ignore[no-any-return,attr-defined] |
| 388 | + |
| 389 | + async def fetch_one(self) -> Model: |
| 390 | + """Fetch one resource, expect exactly one result. |
| 391 | +
|
| 392 | + Returns: |
| 393 | + One resource. |
| 394 | +
|
| 395 | + Raises: |
| 396 | + ValueError: If the total matching records are not exactly one. |
| 397 | + """ |
| 398 | + response = await self._fetch_page_as_response(limit=1, offset=0) |
| 399 | + resource_list = self.make_collection(response) # type: ignore[attr-defined] |
| 400 | + total_records = len(resource_list) |
| 401 | + if resource_list.meta: |
| 402 | + total_records = resource_list.meta.pagination.total |
| 403 | + if total_records == 0: |
| 404 | + raise ValueError("Expected one result, but got zero results") |
| 405 | + if total_records > 1: |
| 406 | + raise ValueError(f"Expected one result, but got {total_records} results") |
| 407 | + |
| 408 | + return resource_list[0] # type: ignore[no-any-return] |
| 409 | + |
| 410 | + async def iterate(self, batch_size: int = 100) -> AsyncIterator[Model]: |
| 411 | + """Iterate over all resources, yielding GenericResource objects. |
| 412 | +
|
| 413 | + Args: |
| 414 | + batch_size: Number of resources to fetch per request |
| 415 | +
|
| 416 | + Returns: |
| 417 | + Iterator of resources. |
| 418 | + """ |
| 419 | + offset = 0 |
| 420 | + limit = batch_size # Default page size |
| 421 | + |
| 422 | + while True: |
| 423 | + response = await self._fetch_page_as_response(limit=limit, offset=offset) |
| 424 | + items_collection = self.make_collection(response) # type: ignore[attr-defined] |
| 425 | + for resource in items_collection: |
| 426 | + yield resource |
| 427 | + |
| 428 | + if not items_collection.meta: |
| 429 | + break |
| 430 | + if not items_collection.meta.pagination.has_next(): |
| 431 | + break |
| 432 | + offset = items_collection.meta.pagination.next_offset() |
| 433 | + |
| 434 | + async def _fetch_page_as_response(self, limit: int = 100, offset: int = 0) -> Response: |
| 435 | + """Fetch one page of resources. |
| 436 | +
|
| 437 | + Returns: |
| 438 | + Response object. |
| 439 | +
|
| 440 | + Raises: |
| 441 | + HTTPStatusError: if the response status code is not 200. |
| 442 | + """ |
| 443 | + pagination_params: dict[str, int] = {"limit": limit, "offset": offset} |
| 444 | + return await self.http_client.request("get", self.build_path(pagination_params)) # type: ignore[attr-defined,no-any-return] |
| 445 | + |
| 446 | + |
| 447 | +class ModifiableResourceMixin[Model](GetMixin[Model], UpdateMixin[Model], DeleteMixin): |
| 448 | + """Editable resource mixin allows to read and update a resource resources.""" |
| 449 | + |
| 450 | + |
| 451 | +class AsyncModifiableResourceMixin[Model]( |
| 452 | + AsyncGetMixin[Model], AsyncUpdateMixin[Model], AsyncDeleteMixin |
| 453 | +): |
| 454 | + """Editable resource mixin allows to read and update a resource resources.""" |
| 455 | + |
| 456 | + |
| 457 | +class ManagedResourceMixin[Model](CreateMixin[Model], ModifiableResourceMixin[Model]): |
| 458 | + """Managed resource mixin allows to read, create, update and delete a resource resources.""" |
| 459 | + |
| 460 | + |
| 461 | +class AsyncManagedResourceMixin[Model]( |
| 462 | + AsyncCreateMixin[Model], AsyncModifiableResourceMixin[Model] |
| 463 | +): |
| 464 | + """Managed resource mixin allows to read, create, update and delete a resource resources.""" |
0 commit comments