|
| 1 | +from typing import Callable, Dict, Any, Tuple, Generator, List |
| 2 | +from .client import SeamHttpClient |
| 3 | +from niquests import Response, JSONDecodeError |
| 4 | +from .pagination import Pagination |
| 5 | + |
| 6 | + |
| 7 | +class SeamPaginator: |
| 8 | + """ |
| 9 | + Handles pagination for API list endpoints. |
| 10 | +
|
| 11 | + Iterates through pages of results returned by a callable function. |
| 12 | + """ |
| 13 | + |
| 14 | + _FIRST_PAGE = "FIRST_PAGE" |
| 15 | + |
| 16 | + def __init__( |
| 17 | + self, |
| 18 | + client: SeamHttpClient, |
| 19 | + request: Callable, |
| 20 | + params: Dict[str, Any] = None, |
| 21 | + ): |
| 22 | + """ |
| 23 | + Initializes the Paginator. |
| 24 | +
|
| 25 | + Args: |
| 26 | + request: The function to call to fetch a page of data. |
| 27 | + http_client: The Seam HTTP client used in the request. |
| 28 | + params: Initial parameters to pass to the callable function. |
| 29 | + """ |
| 30 | + self._request = request |
| 31 | + self.client = client |
| 32 | + self._params = params or {} |
| 33 | + self._pagination_cache: Dict[str, Pagination] = {} |
| 34 | + |
| 35 | + def first_page(self) -> Tuple[List[Any], Pagination | None]: |
| 36 | + """Fetches the first page of results.""" |
| 37 | + self.client.hooks["response"].append( |
| 38 | + lambda response: self._cache_pagination(response, self._FIRST_PAGE) |
| 39 | + ) |
| 40 | + data = self._request(**self._params) |
| 41 | + self.client.hooks["response"].pop() |
| 42 | + |
| 43 | + pagination = self._pagination_cache.get(self._FIRST_PAGE) |
| 44 | + |
| 45 | + return data, pagination |
| 46 | + |
| 47 | + def next_page( |
| 48 | + self, next_page_cursor: str, / |
| 49 | + ) -> Tuple[List[Any], Pagination | None]: |
| 50 | + """Fetches the next page of results using a cursor.""" |
| 51 | + if not next_page_cursor: |
| 52 | + raise ValueError("Cannot get the next page with a null next_page_cursor.") |
| 53 | + |
| 54 | + params = { |
| 55 | + **self._params, |
| 56 | + "page_cursor": next_page_cursor, |
| 57 | + } |
| 58 | + |
| 59 | + self.client.hooks["response"].append( |
| 60 | + lambda response: self._cache_pagination(response, next_page_cursor) |
| 61 | + ) |
| 62 | + data = self._request(**params) |
| 63 | + self.client.hooks["response"].pop() |
| 64 | + |
| 65 | + pagination = self._pagination_cache.get(next_page_cursor) |
| 66 | + |
| 67 | + return data, pagination |
| 68 | + |
| 69 | + def flatten_to_list(self) -> List[Any]: |
| 70 | + """Fetches all pages and returns all items as a single list.""" |
| 71 | + all_items = [] |
| 72 | + current_items, pagination = self.first_page() |
| 73 | + |
| 74 | + if current_items: |
| 75 | + all_items.extend(current_items) |
| 76 | + |
| 77 | + while pagination.has_next_page: |
| 78 | + current_items, pagination = self.next_page(pagination.next_page_cursor) |
| 79 | + if current_items: |
| 80 | + all_items.extend(current_items) |
| 81 | + |
| 82 | + return all_items |
| 83 | + |
| 84 | + def flatten(self) -> Generator[Any, None, None]: |
| 85 | + """Fetches all pages and yields items one by one using a generator.""" |
| 86 | + current_items, pagination = self.first_page() |
| 87 | + if current_items: |
| 88 | + yield from current_items |
| 89 | + |
| 90 | + while pagination and pagination.has_next_page and pagination.next_page_cursor: |
| 91 | + current_items, pagination = self.next_page(pagination.next_page_cursor) |
| 92 | + if current_items: |
| 93 | + yield from current_items |
| 94 | + |
| 95 | + def _cache_pagination(self, response: Response, page_key: str) -> None: |
| 96 | + """Extracts pagination dict from response, creates Pagination object, and caches it.""" |
| 97 | + try: |
| 98 | + response_json = response.json() |
| 99 | + pagination = response_json.get("pagination", {}) |
| 100 | + except JSONDecodeError: |
| 101 | + pagination = {} |
| 102 | + |
| 103 | + if isinstance(pagination, dict): |
| 104 | + self._pagination_cache[page_key] = Pagination( |
| 105 | + has_next_page=pagination.get("has_next_page", False), |
| 106 | + next_page_cursor=pagination.get("next_page_cursor"), |
| 107 | + next_page_url=pagination.get("next_page_url"), |
| 108 | + ) |
0 commit comments