Sha256: d8fa90f368f50a17164556a6b6cb7dff8bb9d185a5bb97c6721a62561d38771d

Contents?: true

Size: 1.09 KB

Versions: 2

Compression:

Stored size: 1.09 KB

Contents

# frozen_string_literal: true

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
          (2..(total_pages - 1)).each do |page|
            @api.request(base_url, filters.merge(page: page))
              .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

2 entries across 2 versions & 1 rubygems

Version Path
shoptet-0.0.35 lib/shoptet/api_enumerator.rb
shoptet-0.0.34 lib/shoptet/api_enumerator.rb