Skip to content

Instantly share code, notes, and snippets.

@leechunhoe
Last active November 29, 2018 08:08
Show Gist options
  • Select an option

  • Save leechunhoe/7ac83a35654b5188c48271f6a056fda5 to your computer and use it in GitHub Desktop.

Select an option

Save leechunhoe/7ac83a35654b5188c48271f6a056fda5 to your computer and use it in GitHub Desktop.
GraphQL type to be extended for offset pagination
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