Module: PolyglotIos::Helper::Depaginate

Included in:
Resource::Base
Defined in:
lib/ios_polyglot_cli/helpers/depaginate.rb

Constant Summary collapse

PER_PAGE =
100

Instance Method Summary collapse

Instance Method Details

#depaginate_query(query) ⇒ Object



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/ios_polyglot_cli/helpers/depaginate.rb', line 8

def depaginate_query(query)
  # Polyglot has custom parameters for pagination
  JsonApiClient::Paginating::Paginator.page_param = "number"
  JsonApiClient::Paginating::Paginator.per_page_param = "size"

  first_page = query.page(1).per(PER_PAGE).all

  # Early return if there's only one page
  return first_page if first_page.meta.total_pages <= 1

  page_numbers_to_fetch = (2..first_page.meta.total_pages).to_a

  items = Parallel
    .map(page_numbers_to_fetch) { |page_number| query.page(page_number).per(PER_PAGE).all }
    .append(first_page) # Fetched pages contain pages from 2 to n, so we need to add the first page
    .sort_by { |page| page.meta.current_page }
    .flat_map { |page| page.to_a }

  items
end