debian-mirror-gitlab/lib/bitbucket_server/paginator.rb

60 lines
1.1 KiB
Ruby
Raw Permalink Normal View History

2018-11-18 11:00:15 +05:30
# frozen_string_literal: true
module BitbucketServer
class Paginator
PAGE_LENGTH = 25
2018-12-13 13:39:08 +05:30
attr_reader :page_offset
def initialize(connection, url, type, page_offset: 0, limit: nil)
2018-11-18 11:00:15 +05:30
@connection = connection
@type = type
@url = url
@page = nil
2018-12-13 13:39:08 +05:30
@page_offset = page_offset
2019-02-13 22:33:31 +05:30
@limit = limit
2018-12-13 13:39:08 +05:30
@total = 0
2018-11-18 11:00:15 +05:30
end
def items
raise StopIteration unless has_next_page?
2018-12-13 13:39:08 +05:30
raise StopIteration if over_limit?
2018-11-18 11:00:15 +05:30
@page = fetch_next_page
2018-12-13 13:39:08 +05:30
@total += @page.items.count
2018-11-18 11:00:15 +05:30
@page.items
end
2018-12-13 13:39:08 +05:30
def has_next_page?
page.nil? || page.next?
end
2018-11-18 11:00:15 +05:30
private
2018-12-13 13:39:08 +05:30
attr_reader :connection, :page, :url, :type, :limit
2018-11-18 11:00:15 +05:30
2018-12-13 13:39:08 +05:30
def over_limit?
2019-02-13 22:33:31 +05:30
return false unless @limit
2018-12-13 13:39:08 +05:30
@limit.positive? && @total >= @limit
2018-11-18 11:00:15 +05:30
end
def next_offset
2018-12-13 13:39:08 +05:30
page.nil? ? starting_offset : page.next
end
def starting_offset
2019-02-13 22:33:31 +05:30
[0, page_offset - 1].max * max_per_page
end
def max_per_page
limit || PAGE_LENGTH
2018-11-18 11:00:15 +05:30
end
def fetch_next_page
2019-02-13 22:33:31 +05:30
parsed_response = connection.get(@url, start: next_offset, limit: max_per_page)
2018-11-18 11:00:15 +05:30
Page.new(parsed_response, type)
end
end
end