|
| 1 | +# -*- coding: utf-8 -*- |
| 2 | + |
| 3 | +import six |
| 4 | +from intercom import HttpError |
| 5 | +from intercom import utils |
| 6 | +from intercom.collection_proxy import CollectionProxy |
| 7 | + |
| 8 | +class CursorCollectionProxy(CollectionProxy): |
| 9 | + def __init__(self, client, collection_cls, collection, finder_url, finder_params={}): |
| 10 | + super(CursorCollectionProxy, self).__init__(client, collection_cls, collection,finder_url, finder_params=finder_params) |
| 11 | + self.paging_info = None |
| 12 | + |
| 13 | + def get_page(self, url, params={}): |
| 14 | + # get a page of results |
| 15 | + # from intercom import Intercom |
| 16 | + |
| 17 | + # if there is no url stop iterating |
| 18 | + if url is None: |
| 19 | + raise StopIteration |
| 20 | + |
| 21 | + import pdb; pdb.set_trace() |
| 22 | + if "sort" in params or "query" in params: |
| 23 | + url = f"{url}/search" |
| 24 | + if self.paging_info and "next" in self.paging_info: |
| 25 | + params["pagination"] = { |
| 26 | + "per_page": self.paging_info["per_page"], |
| 27 | + "starting_after": self.paging_info["next"]["starting_after"] |
| 28 | + } |
| 29 | + response = self.client.post(url, params) |
| 30 | + else: |
| 31 | + response = self.client.get(url, params) |
| 32 | + |
| 33 | + if response is None: |
| 34 | + raise HttpError('Http Error - No response entity returned') |
| 35 | + |
| 36 | + # HACK: dealing with the fact that in unstable /tags is returning |
| 37 | + # {'type': 'list', 'data': []} instead of |
| 38 | + # {'type': 'tags.list', 'tags': []} |
| 39 | + if response['type'] == 'list': |
| 40 | + collection = response['data'] |
| 41 | + else: |
| 42 | + collection = response[self.collection] |
| 43 | + # if there are no resources in the response stop iterating |
| 44 | + if collection is None: |
| 45 | + raise StopIteration |
| 46 | + |
| 47 | + # create the resource iterator |
| 48 | + self.resources = iter(collection) |
| 49 | + # grab the next page URL if one exists |
| 50 | + self.next_page = self.extract_next_link(response) |
| 51 | + |
| 52 | + def get_next_page(self): |
| 53 | + # get the next page of results |
| 54 | + return self.get_page(self.next_page, self.finder_params) |
| 55 | + |
| 56 | + def extract_next_link(self, response): |
| 57 | + if self.paging_info_present(response): |
| 58 | + self.paging_info = response["pages"] |
| 59 | + print(self.paging_info) |
| 60 | + if "next" in self.paging_info: |
| 61 | + # '/users?per_page=50&page=2' |
| 62 | + # {'page': 2, 'starting_after': 'WzE1NzkxODQzNDEwMDAsIjVlMTZmOTg3MWEzNmFiMTFjMDY2YmMzZSIsMl0='} |
| 63 | + if self.finder_params: |
| 64 | + return '/{}'.format(self.collection) |
| 65 | + else: |
| 66 | + return '/{}?page={}&starting_after={}'.format( |
| 67 | + self.collection, |
| 68 | + self.paging_info["next"]["page"], |
| 69 | + self.paging_info["next"]["starting_after"]) |
0 commit comments