Last active
November 29, 2018 08:08
-
-
Save leechunhoe/7ac83a35654b5188c48271f6a056fda5 to your computer and use it in GitHub Desktop.
GraphQL type to be extended for offset pagination
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class Types::PageableType < GraphQL::ObjectType | |
| # Generalised pagination | |
| def define_connection(**kwargs, &block) | |
| this_type = self | |
| super do | |
| field :edges do | |
| type !types[this_type] | |
| resolve ->(obj, args, _ctx) { | |
| page = obj.arguments[:page] || 1 | |
| perPage = obj.arguments[:perPage] || 20 | |
| obj.nodes.limit(perPage).offset((page - 1) * perPage) | |
| } | |
| end | |
| field :pageInfo do | |
| type Types::PageInfoType | |
| resolve ->(obj, args, _ctx) { | |
| page = obj.arguments[:page] || 1 | |
| perPage = obj.arguments[:perPage] || 20 | |
| total = obj.nodes.count || 0 | |
| totalPage = total.fdiv(perPage).ceil | |
| OpenStruct.new( | |
| total: total, | |
| current_page: page, | |
| total_page: totalPage, | |
| per_page: perPage | |
| ) | |
| } | |
| end | |
| end | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment