From 8b2555e6aaae09cc9b3ace0200d7b7af44155752 Mon Sep 17 00:00:00 2001 From: Robert Mosolgo Date: Thu, 24 Oct 2024 16:22:10 -0400 Subject: [PATCH] Don't require input object argument when default value is configured --- lib/graphql/schema/input_object.rb | 2 +- spec/graphql/schema/argument_spec.rb | 31 ++++++++++++++++++++++++++++ 2 files changed, 32 insertions(+), 1 deletion(-) diff --git a/lib/graphql/schema/input_object.rb b/lib/graphql/schema/input_object.rb index d04b0289e4..737ada8d78 100644 --- a/lib/graphql/schema/input_object.rb +++ b/lib/graphql/schema/input_object.rb @@ -163,7 +163,7 @@ def validate_non_null_input(input, ctx, max_errors: nil) # Inject missing required arguments missing_required_inputs = ctx.types.arguments(self).reduce({}) do |m, (argument)| - if !input.key?(argument.graphql_name) && argument.type.non_null? && types.argument(self, argument.graphql_name) + if !input.key?(argument.graphql_name) && argument.type.non_null? && !argument.default_value? && types.argument(self, argument.graphql_name) m[argument.graphql_name] = nil end diff --git a/spec/graphql/schema/argument_spec.rb b/spec/graphql/schema/argument_spec.rb index 2e8c88189d..b9b0ffddb8 100644 --- a/spec/graphql/schema/argument_spec.rb +++ b/spec/graphql/schema/argument_spec.rb @@ -766,4 +766,35 @@ def test; end assert_equal expected_errors, schema.execute(query).to_h['errors'] end end + + describe "default values for non-null input object arguments when not present in variables" do + class InputObjectArgumentWithDefaultValueSchema < GraphQL::Schema + class Add < GraphQL::Schema::Resolver + class AddInput < GraphQL::Schema::InputObject + argument :a, Integer + argument :b, Integer + argument :c, Integer, default_value: 10 + end + + argument :input, AddInput + type(Integer, null: false) + + def resolve(input:) + input[:a] + input[:b] + input[:c] + end + end + class Query < GraphQL::Schema::Object + field :add, resolver: Add + end + query(Query) + end + + it "uses the default value" do + res1 = InputObjectArgumentWithDefaultValueSchema.execute("{ add(input: { a: 1, b: 2 })}") + assert_equal 13, res1["data"]["add"] + + res2 = InputObjectArgumentWithDefaultValueSchema.execute("query Add($input: AddInput!) { add(input: $input) }", variables: { input: { a: 1, b: 4 } }) + assert_equal 15, res2["data"]["add"] + end + end end