Skip to content

Commit 6bf3b31

Browse files
committed
Return a lazy enumerator when no block given to #paginate
1 parent d81eb5d commit 6bf3b31

3 files changed

Lines changed: 49 additions & 10 deletions

File tree

README.md

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -160,6 +160,13 @@ pager.execute(query, :foo => 123) do |page|
160160
end
161161
```
162162

163+
If a block is not given an `Enumerator::Lazy` instance is returned that will fetch the next page upon each iteration:
164+
165+
```rb
166+
results = pager.execute(query, :foo => 123)
167+
results.each { |page| ... }
168+
```
169+
163170
#### `after` Pagination
164171

165172
To use `after` pagination, i.e., to paginate forward, your query must:

lib/shopify_api/graphql/tiny.rb

Lines changed: 13 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -348,19 +348,22 @@ def execute(q, variables = nil)
348348
variables ||= {}
349349
pagination_finder = @options[@options[:direction]]
350350

351-
loop do
352-
page = @gql.execute(q, variables)
351+
enumerator = Enumerator.new do |y|
352+
loop do
353+
page = @gql.execute(q, variables)
354+
y << page
353355

354-
yield page
356+
cursor = pagination_finder[page]
357+
break unless cursor
355358

356-
cursor = pagination_finder[page]
357-
break unless cursor
358-
359-
next_page_variables = variables.dup
360-
next_page_variables[@options[:variable]] = cursor
361-
#break unless next_page_variables != variables
359+
variables[@options[:variable]] = cursor
360+
end
361+
end
362362

363-
variables = next_page_variables
363+
if block_given?
364+
enumerator.each { |page| yield page }
365+
else
366+
enumerator.lazy
364367
end
365368
end
366369

spec/shopify_api/graphql/tiny_spec.rb

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -456,6 +456,35 @@ def paginate_positions(pager, q, options)
456456
expect(positions).to eq positions.sort
457457
end
458458

459+
it "paginates using a lazy enumerator when no block is given" do
460+
q = <<-GQL
461+
query product($id: ID! $after: String) {
462+
product(id: $id) {
463+
variants(first:1 sortKey: POSITION after: $after ) {
464+
pageInfo {
465+
hasNextPage
466+
endCursor
467+
}
468+
edges {
469+
node {
470+
position
471+
}
472+
}
473+
}
474+
}
475+
}
476+
GQL
477+
478+
enum = client.paginate.execute(q, :id => @id)
479+
expect(enum).to be_a(Enumerator::Lazy)
480+
481+
positions = []
482+
enum.each { |page| positions << page.dig(*position_node_at(0)).fetch("position") }
483+
484+
expect(positions.size).to be > 1, VARIANT_COUNT_ERROR
485+
expect(positions).to eq positions.sort
486+
end
487+
459488
it "pages backward using a $before variable when :before pagination is specified" do
460489
q = <<-GQL
461490
query product($id: ID!) {

0 commit comments

Comments
 (0)