Created
November 14, 2023 15:02
-
-
Save rmosolgo/8cec823e748e1444bcf60b66961f22a4 to your computer and use it in GitHub Desktop.
Only allow one root selection with GraphQL-Ruby
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
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