Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Validate default values #3448

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 13 additions & 3 deletions lib/graphql/schema/argument.rb
Original file line number Diff line number Diff line change
Expand Up @@ -301,18 +301,28 @@ def coerce_into_values(parent_object, values, context, argument_values)

private

def validate_input_type(input_type)
def validate_input_type(input_type, wrapped: false)
if input_type.is_a?(String) || input_type.is_a?(GraphQL::Schema::LateBoundType)
# Do nothing; assume this will be validated later
false
elsif input_type.kind.non_null? || input_type.kind.list?
validate_input_type(input_type.unwrap)
type_ready = validate_input_type(input_type.unwrap, wrapped: true)
validate_default_value(default_value, input_type) if default_value? && type_ready && !wrapped
type_ready
elsif !input_type.kind.input?
raise ArgumentError, "Invalid input type for #{path}: #{input_type.graphql_name}. Must be scalar, enum, or input object, not #{input_type.kind.name}."
else
# It's an input type, we're OK
# It's an input type, the type itself is OK but make sure the default conforms
validate_default_value(default_value, input_type) if default_value? && !wrapped
true
end
end

def validate_default_value(default_value, input_type)
default_value = input_type.coerce_isolated_result(default_value) unless default_value.nil?
raise "BOOM" unless input_type.valid_isolated_input?(default_value)
end

def validate_deprecated_or_optional(null:, deprecation_reason:)
if deprecation_reason && !null
raise ArgumentError, "Required arguments cannot be deprecated: #{path}."
Expand Down
7 changes: 7 additions & 0 deletions spec/graphql/schema/argument_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -209,6 +209,13 @@ def self.object_from_id(id, ctx)
res = SchemaArgumentTest::Schema.execute(query_str)
assert_equal "Argument 'requiredWithDefaultArg' on Field 'field' has an invalid value (null). Expected type 'Int!'.", res['errors'][0]['message']
end

it 'validates the type of the default value' do
arg = GraphQL::Schema::Argument.new("my_arg", GraphQL::Types::Int, required: true, owner: nil, default_value: "a_string")
assert_raises(StandardError) do
arg.type
end
end
end

describe 'loads' do
Expand Down