Skip to content

Instantly share code, notes, and snippets.

@rmosolgo
Created December 27, 2024 14:46
Show Gist options
  • Save rmosolgo/3abd5b068c47a1e9c34a7ff446fa88e0 to your computer and use it in GitHub Desktop.
Save rmosolgo/3abd5b068c47a1e9c34a7ff446fa88e0 to your computer and use it in GitHub Desktop.
Ways to customize automatically generated connection types in GraphQL-Ruby
require "bundler/inline"
gemfile do
gem "graphql", "2.4.8"
end
class Thing < GraphQL::Schema::Object
field :name, String
# One option is to extend this method to rename the returned type.
# Only rename it the first time this method is called (when there's no `@connection_type`)
def self.connection_type
if !@connection_type
conn_type = super
conn_type.graphql_name("AnotherCustomThingConnection")
conn_type
else
@connection_type
end
end
end
# Another option is to make a "real" Ruby class based on `.connection_type_class`, which is the parent class
# for generated `.connection_type` classes.
#
# You could use this class directly for `field ...` configurations.
#
class CustomThingConnection < Thing.connection_type_class
# This method adds all the connection-related fields
edge_type(Thing.edge_type)
end
class CustomThing < Thing
# Another option is to override `.connection_type` to return your custom-made class
# (instead of letting GraphQL-Ruby automatically generate one when this method is first called)
def self.connection_type
CustomThingConnection
end
end
# Just to demonstrate that these create the expected types:
class MySchema < GraphQL::Schema
extra_types(CustomThing.connection_type, Thing.connection_type)
end
puts MySchema.to_definition
# """
# The connection type for Thing.
# """
# type AnotherCustomThingConnection {
# """
# A list of edges.
# """
# edges: [ThingEdge]
#
# """
# A list of nodes.
# """
# nodes: [Thing]
#
# """
# Information to aid in pagination.
# """
# pageInfo: PageInfo!
# }
#
# """
# The connection type for Thing.
# """
# type CustomThingConnection {
# """
# A list of edges.
# """
# edges: [ThingEdge]
#
# """
# A list of nodes.
# """
# nodes: [Thing]
#
# """
# Information to aid in pagination.
# """
# pageInfo: PageInfo!
# }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment