Skip to content

Instantly share code, notes, and snippets.

@rmosolgo
Created November 14, 2023 15:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rmosolgo/8cec823e748e1444bcf60b66961f22a4 to your computer and use it in GitHub Desktop.
Save rmosolgo/8cec823e748e1444bcf60b66961f22a4 to your computer and use it in GitHub Desktop.
Only allow one root selection with GraphQL-Ruby
require "bundler/inline"
gemfile do
gem "graphql", "2.1.6"
end
class MySchema < GraphQL::Schema
class Query < GraphQL::Schema::Object
field :f1, Int
field :f2, Int
end
module PermitOnlyOneOperation
def execute_query(query:)
if query.selected_operation.selections.size > 1
raise GraphQL::ExecutionError, "Only one root selection is allowed per operation, but this query includes #{query.selected_operation.selections.size}. Remove one of them and try again."
end
super
end
end
query(Query)
trace_with(PermitOnlyOneOperation)
end
data = { f1: 1, f2: 2 }
pp MySchema.execute("{ f1 f2 }", root_value: data).to_h
# {"errors"=>[{"message"=>"Only one root selection is allowed per operation, but this query includes 2. Remove one of them and try again."}]}
pp MySchema.execute("{ f1 }", root_value: data).to_h
# {"data"=>{"f1"=>1}}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment