lib/wcc/contentful/simple_client/response.rb in wcc-contentful-1.1.2 vs lib/wcc/contentful/simple_client/response.rb in wcc-contentful-1.2.0

- old
+ new

@@ -47,20 +47,19 @@ page_items.length + skip < total end def next_page return unless next_page? - return @next_page if @next_page query = (@request[:query] || {}).merge({ skip: page_items.length + skip }) np = _instrument 'page', url: @request[:url], query: query do @client.get(@request[:url], query) end - @next_page = np.assert_ok! + np.assert_ok! end def initialize(client, request, raw_response) @client = client @request = request @@ -75,21 +74,12 @@ end def each_page(&block) raise ArgumentError, 'Not a collection response' unless page_items - ret = - Enumerator.new do |y| - y << self + ret = PaginatingEnumerable.new(self) - if next_page? - next_page.each_page.each do |page| - y << page - end - end - end - if block_given? ret.map(&block) else ret.lazy end @@ -116,15 +106,10 @@ def includes @includes ||= raw.dig('includes')&.each_with_object({}) do |(_t, entries), h| entries.each { |e| h[e.dig('sys', 'id')] = e } end || {} - - return @includes unless @next_page - - # This could be more efficient - maybe not worth worrying about - @includes.merge(@next_page.includes) end end class SyncResponse < Response def initialize(response) @@ -142,12 +127,12 @@ next_page = _instrument 'page', url: url do @client.get(url) end - @next_page ||= SyncResponse.new(next_page) - @next_page.assert_ok! + next_page = SyncResponse.new(next_page) + next_page.assert_ok! end def next_sync_token # If we haven't grabbed the next page yet, then our next "sync" will be getting # the next page. We could just as easily call sync again with that token. @@ -158,21 +143,12 @@ end def each_page raise ArgumentError, 'Not a collection response' unless page_items - ret = - Enumerator.new do |y| - y << self + ret = PaginatingEnumerable.new(self) - if next_page? - next_page.each_page.each do |page| - y << page - end - end - end - if block_given? ret.map(&block) else ret.lazy end @@ -185,9 +161,29 @@ def self.parse_sync_token(url) url = URI.parse(url) q = CGI.parse(url.query) q['sync_token']&.first + end + end + + class PaginatingEnumerable + include Enumerable + + def initialize(initial_page) + raise ArgumentError, 'Must provide initial page' unless initial_page.present? + + @initial_page = initial_page + end + + def each + page = @initial_page + yield page + + while page.next_page? + page = page.next_page + yield page + end end end class ApiError < StandardError attr_reader :response