11from typing import Callable , Dict , Any , Tuple , Generator , List
2+ from .client import SeamHttpClient
3+ from niquests import Response , JSONDecodeError
24
35
46class Pagination :
@@ -22,28 +24,33 @@ class Paginator:
2224
2325 _FIRST_PAGE = "FIRST_PAGE"
2426
25- def __init__ (self , request : Callable , params : Dict [str , Any ] = None ):
27+ def __init__ (
28+ self ,
29+ request : Callable ,
30+ http_client : SeamHttpClient ,
31+ params : Dict [str , Any ] = None ,
32+ ):
2633 """
2734 Initializes the Paginator.
2835
2936 Args:
3037 request: The function to call to fetch a page of data.
38+ http_client: The HTTP client used in the request.
3139 params: Initial parameters to pass to the callable function.
3240 """
3341 self ._request = request
42+ self ._http_client = http_client
3443 self ._params = params or {}
3544 self ._pagination_cache : Dict [str , Pagination ] = {}
3645
3746 def first_page (self ) -> Tuple [List [Any ], Pagination | None ]:
3847 """Fetches the first page of results."""
39- params = {
40- ** self ._params ,
41- "on_response" : lambda response : self ._cache_pagination (
42- response , self ._FIRST_PAGE
43- ),
44- }
48+ self ._http_client .hooks ["response" ].append (
49+ lambda response : self ._cache_pagination (response , self ._FIRST_PAGE )
50+ )
51+ data = self ._request (** self ._params )
52+ self ._http_client .hooks ["response" ].pop ()
4553
46- data = self ._request (** params )
4754 pagination = self ._pagination_cache .get (self ._FIRST_PAGE )
4855
4956 return data , pagination
@@ -56,12 +63,14 @@ def next_page(self, next_page_cursor: str) -> Tuple[List[Any], Pagination | None
5663 params = {
5764 ** self ._params ,
5865 "page_cursor" : next_page_cursor ,
59- "on_response" : lambda response : self ._cache_pagination (
60- response , next_page_cursor
61- ),
6266 }
6367
68+ self ._http_client .hooks ["response" ].append (
69+ lambda response : self ._cache_pagination (response , next_page_cursor )
70+ )
6471 data = self ._request (** params )
72+ self ._http_client .hooks ["response" ].pop ()
73+
6574 pagination = self ._pagination_cache .get (next_page_cursor )
6675
6776 return data , pagination
@@ -92,9 +101,13 @@ def flatten(self) -> Generator[Any, None, None]:
92101 if current_items :
93102 yield from current_items
94103
95- def _cache_pagination (self , response : Dict [ str , Any ] , page_key : str ) -> None :
104+ def _cache_pagination (self , response : Response , page_key : str ) -> None :
96105 """Extracts pagination dict from response, creates Pagination object, and caches it."""
97- pagination = response .get ("pagination" , {})
106+ try :
107+ response_json = response .json ()
108+ pagination = response_json .get ("pagination" , {})
109+ except JSONDecodeError :
110+ pagination = {}
98111
99112 if isinstance (pagination , dict ):
100113 self ._pagination_cache [page_key ] = Pagination (
0 commit comments