Created
July 23, 2024 15:54
-
-
Save rmosolgo/151fc2ec7f8fc351e88c7f4d99325bbe to your computer and use it in GitHub Desktop.
GraphQL-Ruby Connection with Custom Arguments
This file contains 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
# GraphQL-Ruby's connection system automatically adds first, last, after and before arguments. | |
# If you don't want all of those, you have to disable the system with `connection: false` | |
# in the field definition, then re-enable it manually. | |
# | |
# In this case, to create a field without the `last` argument, I created a custom subclass of `ConnectionExtension` | |
# which doesn't add any arguments. Then I add the specific arguments I want in the field definition. | |
# (I could also add those arguments in `def apply` using `field.argument ...`.) | |
require "bundler/inline" | |
gemfile do | |
gem "graphql", "2.3.10" | |
end | |
class ExampleSchema < GraphQL::Schema | |
class Thing < GraphQL::Schema::Object | |
field :name, String | |
end | |
class ConnectionWithoutArgumentsExtension < GraphQL::Schema::Field::ConnectionExtension | |
def apply | |
# no-op -- don't add arguments | |
end | |
end | |
class Query < GraphQL::Schema::Object | |
field :things, Thing.connection_type, connection: false, extensions: [ConnectionWithoutArgumentsExtension] do | |
argument :after, "String", "Returns the elements in the list that come after the specified cursor.", required: false | |
argument :before, "String", "Returns the elements in the list that come before the specified cursor.", required: false | |
argument :first, "Int", "Returns the first _n_ elements from the list.", required: false | |
end | |
def things | |
[{name: "Abacus"}, {name: "Beach Ball"}, {name: "Costume"}, {name: "Dandelion"}] | |
end | |
end | |
query(Query) | |
end | |
puts ExampleSchema.to_definition | |
### | |
# ... | |
# | |
# type Query { | |
# things( | |
# """ | |
# Returns the elements in the list that come after the specified cursor. | |
# """ | |
# after: String | |
# """ | |
# Returns the elements in the list that come before the specified cursor. | |
# """ | |
# before: String | |
# """ | |
# Returns the first _n_ elements from the list. | |
# """ | |
# first: Int | |
# ): ThingConnection | |
# } | |
# | |
# ... | |
### | |
pp ExampleSchema.execute("{ things(first: 2) { nodes { name } } }").to_h | |
# {"data"=>{"things"=>{"nodes"=>[{"name"=>"Abacus"}, {"name"=>"Beach Ball"}]}}} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment