2018-07-25 08:22:53 -04:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
2018-06-25 16:06:10 -04:00
|
|
|
module BitbucketServer
|
|
|
|
class Paginator
|
2018-07-06 00:11:16 -04:00
|
|
|
PAGE_LENGTH = 25
|
2018-06-25 16:06:10 -04:00
|
|
|
|
2018-11-05 18:37:21 -05:00
|
|
|
attr_reader :page_offset
|
|
|
|
|
|
|
|
def initialize(connection, url, type, page_offset: 0, limit: nil)
|
2018-06-25 16:06:10 -04:00
|
|
|
@connection = connection
|
|
|
|
@type = type
|
|
|
|
@url = url
|
|
|
|
@page = nil
|
2018-11-05 18:37:21 -05:00
|
|
|
@page_offset = page_offset
|
2019-01-07 00:09:41 -05:00
|
|
|
@limit = limit
|
2018-11-05 18:37:21 -05:00
|
|
|
@total = 0
|
2018-06-25 16:06:10 -04:00
|
|
|
end
|
|
|
|
|
|
|
|
def items
|
|
|
|
raise StopIteration unless has_next_page?
|
2018-11-05 18:37:21 -05:00
|
|
|
raise StopIteration if over_limit?
|
2018-06-25 16:06:10 -04:00
|
|
|
|
|
|
|
@page = fetch_next_page
|
2018-11-05 18:37:21 -05:00
|
|
|
@total += @page.items.count
|
2018-06-25 16:06:10 -04:00
|
|
|
@page.items
|
|
|
|
end
|
|
|
|
|
2018-11-05 18:37:21 -05:00
|
|
|
def has_next_page?
|
|
|
|
page.nil? || page.next?
|
|
|
|
end
|
|
|
|
|
2018-06-25 16:06:10 -04:00
|
|
|
private
|
|
|
|
|
2018-11-05 18:37:21 -05:00
|
|
|
attr_reader :connection, :page, :url, :type, :limit
|
2018-06-25 16:06:10 -04:00
|
|
|
|
2018-11-05 18:37:21 -05:00
|
|
|
def over_limit?
|
2019-01-07 00:09:41 -05:00
|
|
|
return false unless @limit
|
|
|
|
|
2020-08-05 11:09:59 -04:00
|
|
|
@limit > 0 && @total >= @limit
|
2018-06-25 16:06:10 -04:00
|
|
|
end
|
|
|
|
|
2018-07-06 00:11:16 -04:00
|
|
|
def next_offset
|
2018-11-05 18:37:21 -05:00
|
|
|
page.nil? ? starting_offset : page.next
|
|
|
|
end
|
|
|
|
|
|
|
|
def starting_offset
|
2019-01-07 00:09:41 -05:00
|
|
|
[0, page_offset - 1].max * max_per_page
|
|
|
|
end
|
|
|
|
|
|
|
|
def max_per_page
|
|
|
|
limit || PAGE_LENGTH
|
2018-06-25 16:06:10 -04:00
|
|
|
end
|
|
|
|
|
|
|
|
def fetch_next_page
|
2019-01-07 00:09:41 -05:00
|
|
|
parsed_response = connection.get(@url, start: next_offset, limit: max_per_page)
|
2018-06-25 16:06:10 -04:00
|
|
|
Page.new(parsed_response, type)
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|