Skip to content

Instantly share code, notes, and snippets.

@MatteoJoliveau
Created June 21, 2018 07:30
Show Gist options
  • Save MatteoJoliveau/df3d51fcecb446f62f2fc0f185cde60b to your computer and use it in GitHub Desktop.
Save MatteoJoliveau/df3d51fcecb446f62f2fc0f185cde60b to your computer and use it in GitHub Desktop.
Pageable interface to paginate with Kaminari in GraphQL Ruby
module Types
module PageableType
include Types::Base::Interface
field :current_page, Integer, null: true
field :previous_page, Integer, null: true, method: :prev_page
field :next_page, Integer, null: true
field :total_pages, Integer, null: true
field :total_items, Integer, null: true, method: :total_count
field :size, Integer, null: true, method: :count
field :first_page, Boolean, null: true, method: :first_page?
field :last_page, Boolean, null: true, method: :last_page?
end
end
@jasonfine
Copy link

Do you have a usage example of this?

@Shaglock
Copy link

Shaglock commented Sep 2, 2019

Would be awesome to see basic usage example of this

@Shaglock
Copy link

Shaglock commented Sep 3, 2019

@jasonfine I got this working.
Basically you need to create collection type which implements this interface and also returns items(or whatever you call it)

module Types
  module Collections
    class Products < Types::BaseObject
      implements Types::PageableType

      field :items, [Types::Product], null: false

      def items
        object
      end
    end
  end
end

And that's it. In query I have field :products, Types::Collections::Products, null: false, and resolve that with kaminari paginated array (Product.all.page(1).per(20)).
I also moved implements and def items parts to BaseCollection class and then I inherit from it. Hope this helps. Thank you @MatteoJoliveau for this interface

Let me know if there is a better approach to this or maybe I did something wrong

@jasonfine
Copy link

Thanks! Really appreciate you mentioning this! I ended up coming up with my own solution (using a proxy class to expose the kaminari AR object methods as GQL fields)

But maybe this will help someone else in the future who finds this.

@MatteoJoliveau
Copy link
Author

Hi guys, sorry I didn't notice the notification.

@Shaglock totally nailed the solution, and the interface is indeed meant to be compatible with Kaminari-like pagination libraries.
Implementing items in a BaseCollection that extends BaseObject is a wonderful idea to keep code DRY.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment