Offset pagination for GraphQL on Rails

You would like to show the list of users and paginate them in offset manner, i.e. fetching users by given page number and batch size, instead of GraphQL default cursor based implementation.

Implementation

  1. Override define_connection method of GraphQL object type.

2. Extend it for the class type that you intend to paginate, user in this case.

Types::UserType = Types::PageableType.define do
name "User"
field :id, types.ID
...
end

3. Use connection for users on query_type.rb, add page and per_page arguments.

Types::QueryType = GraphQL::ObjectType.define do
name "Query"
...
connection :usersConnection, Types::UserType.define_connection do
argument :page, type: types.Int
argument :perPage, type: types.Int
resolve ->(_obj, _args, _ctx) {
User.all
}
end
...
end

4. Problem solved!

Reference:

https://graphqlme.com/2017/09/24/graphql-connections-rails/