|  | 
|  | 1 | +from __future__ import annotations | 
|  | 2 | + | 
|  | 3 | +import copy | 
|  | 4 | +from abc import ABC | 
|  | 5 | +from collections.abc import Iterator | 
|  | 6 | +from typing import Any, Self | 
|  | 7 | + | 
|  | 8 | +import httpx | 
|  | 9 | + | 
|  | 10 | +from mpt_api_client.http.client import MPTClient | 
|  | 11 | +from mpt_api_client.models import Collection, Resource | 
|  | 12 | +from mpt_api_client.rql.query_builder import RQLQuery | 
|  | 13 | + | 
|  | 14 | + | 
|  | 15 | +class CollectionBaseClient[ResourceType: Resource](ABC):  # noqa: WPS214 | 
|  | 16 | +    """Immutable Base client for RESTful resource collections. | 
|  | 17 | +
 | 
|  | 18 | +    Examples: | 
|  | 19 | +        active_orders_cc = order_collection.filter(RQLQuery(status="active")) | 
|  | 20 | +        active_orders = active_orders_cc.order_by("created").iterate() | 
|  | 21 | +        product_active_orders = active_orders_cc.filter(RQLQuery(product__id="PRD-1")).iterate() | 
|  | 22 | +
 | 
|  | 23 | +        new_order = order_collection.create(order_data) | 
|  | 24 | +
 | 
|  | 25 | +    """ | 
|  | 26 | + | 
|  | 27 | +    _endpoint: str | 
|  | 28 | +    _resource_class: type[Resource] | 
|  | 29 | +    _collection_class: type[Collection[Resource]] | 
|  | 30 | + | 
|  | 31 | +    def __init__( | 
|  | 32 | +        self, | 
|  | 33 | +        query_rql: RQLQuery | None = None, | 
|  | 34 | +        client: MPTClient | None = None, | 
|  | 35 | +    ) -> None: | 
|  | 36 | +        self._client = client or MPTClient() | 
|  | 37 | +        self.query_rql: RQLQuery | None = query_rql | 
|  | 38 | +        self.query_order_by: list[str] | None = None | 
|  | 39 | +        self.query_select: list[str] | None = None | 
|  | 40 | + | 
|  | 41 | +    @classmethod | 
|  | 42 | +    def clone(cls, collection_client: CollectionBaseClient[ResourceType]) -> Self: | 
|  | 43 | +        """Create a copy of collection client for immutable operations.""" | 
|  | 44 | +        new_collection = cls( | 
|  | 45 | +            client=collection_client._client, | 
|  | 46 | +            query_rql=collection_client.query_rql, | 
|  | 47 | +        ) | 
|  | 48 | +        new_collection.query_order_by = ( | 
|  | 49 | +            copy.copy(collection_client.query_order_by) | 
|  | 50 | +            if collection_client.query_order_by | 
|  | 51 | +            else None | 
|  | 52 | +        ) | 
|  | 53 | +        new_collection.query_select = ( | 
|  | 54 | +            copy.copy(collection_client.query_select) if collection_client.query_select else None | 
|  | 55 | +        ) | 
|  | 56 | +        return new_collection | 
|  | 57 | + | 
|  | 58 | +    def build_url(self, query_params: dict[str, Any] | None = None) -> str: | 
|  | 59 | +        """Return the endpoint URL.""" | 
|  | 60 | +        query_params = query_params or {} | 
|  | 61 | +        query_parts = [ | 
|  | 62 | +            f"{param_key}={param_value}" for param_key, param_value in query_params.items() | 
|  | 63 | +        ]  # noqa: WPS237 | 
|  | 64 | +        if self.query_order_by: | 
|  | 65 | +            query_parts.append(f"order={','.join(self.query_order_by)}")  # noqa: WPS237 | 
|  | 66 | +        if self.query_select: | 
|  | 67 | +            query_parts.append(f"select={','.join(self.query_select)}")  # noqa: WPS237 | 
|  | 68 | +        if self.query_rql: | 
|  | 69 | +            query_parts.append(str(self.query_rql)) | 
|  | 70 | +        if query_parts: | 
|  | 71 | +            return f"{self._endpoint}?{'&'.join(query_parts)}"  # noqa: WPS237 | 
|  | 72 | +        return self._endpoint | 
|  | 73 | + | 
|  | 74 | +    def order_by(self, *fields: str) -> Self: | 
|  | 75 | +        """Returns new collection with ordering setup. | 
|  | 76 | +
 | 
|  | 77 | +        Raises ValueError if ordering is already set. | 
|  | 78 | +        """ | 
|  | 79 | +        if self.query_order_by is not None: | 
|  | 80 | +            raise ValueError("Ordering is already set. Cannot set ordering multiple times.") | 
|  | 81 | +        new_collection = self.clone(self) | 
|  | 82 | +        new_collection.query_order_by = list(fields) | 
|  | 83 | +        return new_collection | 
|  | 84 | + | 
|  | 85 | +    def filter(self, rql: RQLQuery) -> Self: | 
|  | 86 | +        """Add filter using RQLQuery.""" | 
|  | 87 | +        if self.query_rql: | 
|  | 88 | +            rql = self.query_rql & rql | 
|  | 89 | +        new_collection = self.clone(self) | 
|  | 90 | +        new_collection.query_rql = rql | 
|  | 91 | +        return new_collection | 
|  | 92 | + | 
|  | 93 | +    def select(self, *fields: str) -> Self: | 
|  | 94 | +        """Set select fields. Raises ValueError if select fields are already set.""" | 
|  | 95 | +        if self.query_select is not None: | 
|  | 96 | +            raise ValueError( | 
|  | 97 | +                "Select fields are already set. Cannot set select fields multiple times." | 
|  | 98 | +            ) | 
|  | 99 | + | 
|  | 100 | +        new_client = self.clone(self) | 
|  | 101 | +        new_client.query_select = list(fields) | 
|  | 102 | +        return new_client | 
|  | 103 | + | 
|  | 104 | +    def fetch_page(self, limit: int = 100, offset: int = 0) -> Collection[ResourceType]: | 
|  | 105 | +        """Fetch one page of resources.""" | 
|  | 106 | +        response = self._fetch_page_as_response(limit=limit, offset=offset) | 
|  | 107 | +        return Collection.from_response(response) | 
|  | 108 | + | 
|  | 109 | +    def fetch_one(self) -> ResourceType: | 
|  | 110 | +        """Fetch one page, expect exactly one result.""" | 
|  | 111 | +        response = self._fetch_page_as_response(limit=1, offset=0) | 
|  | 112 | +        resource_list: Collection[ResourceType] = Collection.from_response(response) | 
|  | 113 | +        total_records = len(resource_list) | 
|  | 114 | +        if resource_list.meta: | 
|  | 115 | +            total_records = resource_list.meta.pagination.total | 
|  | 116 | +        if total_records == 0: | 
|  | 117 | +            raise ValueError("Expected one result, but got zero results") | 
|  | 118 | +        if total_records > 1: | 
|  | 119 | +            raise ValueError(f"Expected one result, but got {total_records} results") | 
|  | 120 | + | 
|  | 121 | +        return resource_list[0] | 
|  | 122 | + | 
|  | 123 | +    def iterate(self) -> Iterator[ResourceType]: | 
|  | 124 | +        """Iterate over all resources, yielding GenericResource objects.""" | 
|  | 125 | +        offset = 0 | 
|  | 126 | +        limit = 100  # Default page size | 
|  | 127 | + | 
|  | 128 | +        while True: | 
|  | 129 | +            response = self._fetch_page_as_response(limit=limit, offset=offset) | 
|  | 130 | +            items_collection: Collection[ResourceType] = Collection.from_response(response) | 
|  | 131 | +            yield from items_collection | 
|  | 132 | + | 
|  | 133 | +            if not items_collection.meta: | 
|  | 134 | +                break | 
|  | 135 | +            if not items_collection.meta.pagination.has_next(): | 
|  | 136 | +                break | 
|  | 137 | +            offset = items_collection.meta.pagination.next_offset() | 
|  | 138 | + | 
|  | 139 | +    def create(self, resource_data: dict[str, Any]) -> ResourceType: | 
|  | 140 | +        """Create a new resource using `POST /endpoint`.""" | 
|  | 141 | +        response = self._client.post(self._endpoint, json=resource_data) | 
|  | 142 | +        response.raise_for_status() | 
|  | 143 | + | 
|  | 144 | +        return self._resource_class.from_response(response)  # type: ignore[return-value] | 
|  | 145 | + | 
|  | 146 | +    def _fetch_page_as_response(self, limit: int = 100, offset: int = 0) -> httpx.Response: | 
|  | 147 | +        pagination_params: dict[str, int] = {"limit": limit, "offset": offset} | 
|  | 148 | +        response = self._client.get(self.build_url(pagination_params)) | 
|  | 149 | +        response.raise_for_status() | 
|  | 150 | + | 
|  | 151 | +        return response | 
0 commit comments