All Articles

Cursor based Relay-style pagination in GraphQL-ruby

In the previous blog about Adding offset based pagination in GraphQL-ruby we learned the simplest approach to add pagination. Also, we got an idea about some of the disadvantages of using offset based pagination.

In this blog, let’s discuss a better approach to add pagination to GraphQL query. To add cursor based relay-style pagination we just need to change the return type from Array of PostType to Types::PostType.connection_type. Done. We don’t need to do anymore changes on the server-side.

# app/graphql/resolvers/posts/index.rb

class Resolvers::Posts::Index < GraphQL::Schema::Resolver
  description "List of all the posts"

  type Types::PostType.connection_type, null: false

  def resolve
    Post.all
  end
end

What is the difference between Cursor based pagination and Relay-style cursor based pagination?

I would say nothing much. The only difference is in the format of the GraphQL query.

query FetchPosts($first: Int, $after: String) {
  posts(first: $first, after: $after) {
    pageInfo {
      endCursor
      startCursor
      hasPreviousPage
      hasNextPage
    }
    nodes {
      id
      title
      content
    }
    edges {
      node {
        id
        title
        content
      }
    }
  }
}

The pageInfo object gives details about the current page pagination information. For example, the cursor after which next records needs to be fetched i.e: $after: pageInfo.endCursor. nodes object is the collection of posts and edges is the collection of posts withing node namespace.

Happy Coding!!