Sha256: a3bdacbbdf4c47e726c4cbe1fd4152d71e50280e009f29547d91a50195bd1fc4

Contents?: true

Size: 1.58 KB

Versions: 3

Compression:

Stored size: 1.58 KB

Contents

require_relative 'errors'

module Bunq
  class MissingPaginationObject < UnexpectedResponse; end
  # https://doc.bunq.com/api/1/page/pagination
  class Paginated
    def initialize(resource)
      @resource = resource
    end

    def paginate(count: 200, older_id: nil, newer_id: nil)
      params = setup_params(count, older_id, newer_id)
      @resource.with_session { enumerator(params) }
    end

    private

    def setup_params(count, older_id, newer_id)
      fail ArgumentError.new('Cant pass both older_id and newer_id') if older_id && newer_id

      params = {count: count}
      params[:older_id] = older_id if older_id
      params[:newer_id] = newer_id if newer_id
      params
    end

    def enumerator(params)
      last_page = false
      next_params = params

      Enumerator.new do |yielder|
        loop do
          raise StopIteration if last_page

          result = @resource.get(next_params)
          result['Response'].each do |item|
            yielder << item
          end

          pagination = result['Pagination']
          fail MissingPaginationObject unless pagination

          last_page = !pagination[paging_url(params)]
          next_params = params.merge(:"#{paging_id(params)}" => param(paging_id(params), pagination[paging_url(params)])) unless last_page
        end
      end
    end

    def paging_url(params)
      return 'newer_url' if params[:newer_id]
      'older_url'
    end

    def paging_id(params)
      return 'newer_id' if params[:newer_id]
      'older_id'
    end

    def param(name, url)
      CGI.parse(URI(url).query)[name]&.first
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
bunq-client-0.4.0 lib/bunq/paginated.rb
bunq-client-0.3.0 lib/bunq/paginated.rb
bunq-client-0.2.0 lib/bunq/paginated.rb