Skip to content

Instantly share code, notes, and snippets.

@theorygeek
Created September 6, 2017 14:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save theorygeek/860d0e87291c8975092e15330429c360 to your computer and use it in GitHub Desktop.
Save theorygeek/860d0e87291c8975092e15330429c360 to your computer and use it in GitHub Desktop.
GraphQL Connection Counts
# Monkey Patch: Add a count field to all connections by default.
# Note, I tried to make this nicer, where it would just call the original method and then add a count field,
# but the challenge outlasted my patience. So I just replaced the whole method. TODO: better way to do this
module GraphQL
module Relay
module ConnectionType
def self.create_type(wrapped_type, edge_type: wrapped_type.edge_type, edge_class: GraphQL::Relay::Edge, nodes_field: ConnectionType.default_nodes_field, &block)
custom_edge_class = edge_class
# Any call that would trigger `wrapped_type.ensure_defined`
# must be inside this lazy block, otherwise we get weird
# cyclical dependency errors :S
ObjectType.define do
name("#{wrapped_type.name}Connection")
description("The connection type for #{wrapped_type.name}.")
field :edges, types[edge_type], "A list of edges.", edge_class: custom_edge_class, property: :edge_nodes
if nodes_field
field :nodes, types[wrapped_type], "A list of nodes.", property: :edge_nodes
end
field :pageInfo, !PageInfo, "Information to aid in pagination.", property: :page_info
field :count, !types.Int do
resolve -> (obj, _args, _ctx) { obj.nodes.size }
end
block && instance_eval(&block)
end
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment