Sha256: cf0aa1fef04e683402f1bb6e2eb5020a36aa091a737e6dbaeef1d9e695f5b688

Contents?: true

Size: 1.09 KB

Versions: 12

Compression:

Stored size: 1.09 KB

Contents

class Shoptet
  class ApiEnumerator < SimpleDelegator
    def initialize base_url, filters, data_key, api
      @base_url = base_url
      @filters = filters
      @data_key = data_key || URI(base_url).path.split('/').last
      @api = api

      @enum = Enumerator.new do |y|
        first_page.dig('data', @data_key).each { y.yield _1 }

        if total_pages > 1
          other_pages = 2..(total_pages - 1)
          other_pages.each do |page|
            result = @api.request(base_url, filters.merge(page: page))
            result.dig('data', @data_key).each { y.yield _1 }
          end

          last_page.dig('data', @data_key).each { y.yield _1 }
        end
      end

      super @enum
    end

    def first_page
      @first_page ||= @api.request(@base_url, @filters)
    end

    def last_page
      return first_page if total_pages < 2

      @last_page ||= @api.request(@base_url, @filters.merge(page: total_pages))
    end

    def total_pages
      first_page.dig('data', 'paginator', 'pageCount') || 0
    end

    def size
      first_page.dig('data', 'paginator', 'totalCount')
    end
  end
end

Version data entries

12 entries across 12 versions & 1 rubygems

Version Path
shoptet-0.0.33 lib/shoptet/api_enumerator.rb
shoptet-0.0.32 lib/shoptet/api_enumerator.rb
shoptet-0.0.31 lib/shoptet/api_enumerator.rb
shoptet-0.0.30 lib/shoptet/api_enumerator.rb
shoptet-0.0.29 lib/shoptet/api_enumerator.rb
shoptet-0.0.28 lib/shoptet/api_enumerator.rb
shoptet-0.0.27 lib/shoptet/api_enumerator.rb
shoptet-0.0.26 lib/shoptet/api_enumerator.rb
shoptet-0.0.25 lib/shoptet/api_enumerator.rb
shoptet-0.0.24 lib/shoptet/api_enumerator.rb
shoptet-0.0.23 lib/shoptet/api_enumerator.rb
shoptet-0.0.22 lib/shoptet/api_enumerator.rb