1+ require "intercom/utils"
2+ require "ext/sliceable_hash"
3+
4+ module Intercom
5+ class ScrollCollectionProxy
6+
7+ attr_reader :resource_name , :scroll_url , :resource_class , :scroll_param , :records
8+
9+ def initialize ( resource_name , finder_details : { } , client :)
10+ @resource_name = resource_name
11+ @resource_class = Utils . constantize_resource_name ( resource_name )
12+ @scroll_url = ( finder_details [ :url ] || "/#{ @resource_name } " ) + '/scroll'
13+ @client = client
14+
15+ end
16+
17+ def next ( scroll_parameter = nil )
18+ @records = [ ]
19+ if not scroll_parameter
20+ #First time so do initial get without scroll_param
21+ response_hash = @client . get ( @scroll_url , '' )
22+ else
23+ #Not first call so use get next page
24+ response_hash = @client . get ( @scroll_url , scroll_param : scroll_parameter )
25+ end
26+ raise Intercom ::HttpError . new ( 'Http Error - No response entity returned' ) unless response_hash
27+ @scroll_param = extract_scroll_param ( response_hash )
28+ top_level_entity_key = deserialize_response_hash ( response_hash )
29+ response_hash [ top_level_entity_key ] = response_hash [ top_level_entity_key ] . map do |object_json |
30+ Lib ::TypedJsonDeserializer . new ( object_json ) . deserialize
31+ end
32+ @records = response_hash [ @resource_name ]
33+ self
34+ end
35+
36+ def each ( &block )
37+ scroll_param = nil
38+ loop do
39+ if not scroll_param
40+ response_hash = @client . get ( @scroll_url , '' )
41+ else
42+ response_hash = @client . get ( @scroll_url , scroll_param : scroll_param )
43+ end
44+ raise Intercom ::HttpError . new ( 'Http Error - No response entity returned' ) unless response_hash
45+ response_hash [ deserialize_response_hash ( response_hash ) ] . each do |object_json |
46+ block . call Lib ::TypedJsonDeserializer . new ( object_json ) . deserialize
47+ end
48+ scroll_param = extract_scroll_param ( response_hash )
49+ break if not records_present? ( response_hash )
50+ end
51+ self
52+ end
53+
54+ def []( target_index )
55+ self . each_with_index do |item , index |
56+ return item if index == target_index
57+ end
58+ nil
59+ end
60+
61+ include Enumerable
62+
63+ private
64+
65+ def deserialize_response_hash ( response_hash )
66+ top_level_type = response_hash . delete ( 'type' )
67+ if resource_name == 'subscriptions'
68+ top_level_entity_key = 'items'
69+ else
70+ top_level_entity_key = Utils . entity_key_from_type ( top_level_type )
71+ end
72+ end
73+
74+ def records_present? ( response_hash )
75+ ( response_hash [ @resource_name ] . length > 0 )
76+ end
77+
78+ def extract_scroll_param ( response_hash )
79+ return nil unless records_present? ( response_hash )
80+ response_hash [ 'scroll_param' ]
81+ end
82+ end
83+ end
0 commit comments