Created
November 27, 2024 17:47
-
-
Save rmosolgo/7c14fba8b43f4e4ff472e48284718906 to your computer and use it in GitHub Desktop.
Get a top-level argument from a nested field in GraphQL-Ruby
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
require "bundler/inline" | |
gemfile do | |
gem "graphql", "2.4.4" | |
end | |
class MySchema < GraphQL::Schema | |
class NestedThingInput < GraphQL::Schema::InputObject | |
argument :env, String | |
end | |
class NestedThing < GraphQL::Schema::Object | |
field :nested, NestedThing do | |
argument :input, NestedThingInput, required: false | |
end | |
def nested(input: nil) | |
# Add this value to scoped context so that it will be available to child fields | |
# see https://graphql-ruby.org/queries/executing_queries.html#scoped-context | |
if input | |
context.scoped_set!(:top_level_env, input.env) | |
end | |
:some_nested_thing | |
end | |
field :top_level_env, String | |
def top_level_env | |
# This will have been set by _something_ upstream in the query: | |
context[:top_level_env] | |
end | |
end | |
class Query < GraphQL::Schema::Object | |
field :nested, NestedThing do | |
argument :input, NestedThingInput, required: false | |
end | |
def nested(input: nil) | |
# This is duplicated from NestedThing#nested -- you could use your DRY technique of choice here. | |
if input | |
context.scoped_set!(:top_level_env, input.env) | |
end | |
:some_nested_thing | |
end | |
end | |
query(Query) | |
end | |
# Access the value with shallow nesting: | |
pp MySchema.execute("{ nested(input: { env: \"staging\" }) { nested { topLevelEnv } } }").to_h | |
# {"data"=>{"nested"=>{"nested"=>{"topLevelEnv"=>"staging"}}}} | |
# Access the value with no nesting: | |
pp MySchema.execute("{ nested(input: { env: \"production\" }) { topLevelEnv } }").to_h | |
# {"data"=>{"nested"=>{"topLevelEnv"=>"production"}}} | |
# Access the value with very deep nesting, with an override in the tree: | |
pp MySchema.execute("{ nested(input: { env: \"ignored\" }) { nested { nested { nested(input: { env: \"local-override\" }) { topLevelEnv } } } } }").to_h | |
# {"data"=>{"nested"=>{"nested"=>{"nested"=>{"nested"=>{"topLevelEnv"=>"local-override"}}}}}} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment