Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create stable connection for pagination #37

Merged
merged 1 commit into from
Jan 5, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions app/graphql/sagittarius_schema.rb
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ class SagittariusSchema < GraphQL::Schema
query(Types::QueryType)

default_max_page_size 50
connections.add(ActiveRecord::Relation, Sagittarius::Graphql::StableConnection)

# For batch-loading (see https://graphql-ruby.org/dataloader/overview.html)
use GraphQL::Dataloader
Expand Down
68 changes: 68 additions & 0 deletions lib/sagittarius/graphql/stable_connection.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
# frozen_string_literal: true

module Sagittarius
module Graphql
# rubocop:disable GraphQL/ObjectDescription -- this is a connection implementation, not a GraphQL object
class StableConnection < GraphQL::Pagination::Connection
def cursor_for(item)
encode(item.id.to_s)
end

def backward?
@before_value.present? || @last_value.present?
end

def page_size
if backward?
[@last_value, max_page_size].compact.min
else
[@first_value, max_page_size].compact.min
end
end

def results
@results ||= begin
if backward?
paginate_backward
elsif @after_value.present?
paginate_forward
end

@items.limit(page_size + 1)
end
end

def paginate_backward
before_id = Integer(decode(@before_value), exception: false)
if before_id.nil? && !@before_value.nil?
raise GraphQL::ExecutionError, "Invalid cursor '#{@before_value}' provided"
end

@items = @items.where('id < ?', before_id) unless before_id.nil?
@items = @items.reverse_order
end

def paginate_forward
after_id = Integer(decode(@after_value), exception: false)
raise GraphQL::ExecutionError, "Invalid cursor '#{@after_value}' provided" if after_id.nil?

@items = @items.where('id > ?', after_id)
end

def nodes
results.slice(0, page_size)
end

# rubocop:disable Naming/PredicateName -- this is required by graphql-ruby
def has_next_page
!backward? && results.size > page_size
end

def has_previous_page
backward? && results.size > page_size
end
# rubocop:enable Naming/PredicateName
end
# rubocop:enable GraphQL/ObjectDescription
end
end