Skip to content

Instantly share code, notes, and snippets.

@jorgedavila25
Last active March 11, 2020 14:03
Show Gist options
  • Save jorgedavila25/ab0a51a09fbf4ce36b33cc501dcd02e7 to your computer and use it in GitHub Desktop.
Save jorgedavila25/ab0a51a09fbf4ce36b33cc501dcd02e7 to your computer and use it in GitHub Desktop.
Using Ruby's ElasticSearch gem that uses Kaminari for pagination and the Ruby GraphQL gem, this is a custom connection to bypass additional pagination. This assumes that you've already queried the correct paginated records from ElasticSearch and you're returning an `Elasticsearch::Model::Response` object.
class ElasticSearchConnection < GraphQL::Relay::BaseConnection
def has_next_page
!nodes.last_page?
end
def has_previous_page
!nodes.first_page?
end
def cursor_from_node(node)
if nodes.current_page == 1
starting_offset = 0
else
starting_offset = nodes.limit_value * (nodes.current_page - 1)
end
idx = starting_offset + (sliced_nodes.find_index(node) + 1)
Base64.strict_encode64(idx.to_s)
end
def start_cursor
cursor_from_node(nodes.to_a.first)
end
def end_cursor
cursor_from_node(nodes.to_a.last)
end
private
def paged_nodes
sliced_nodes
end
def sliced_nodes
nodes.records
end
end
# Register the custom connection
GraphQL::Relay::BaseConnection.register_connection_implementation(
Kaminari::PageScopeMethods,
ElasticSearchConnection
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment