Skip to content

Commit

Permalink
Merge pull request #4933 from engwan/fix-prepare-on-list-of-input-obj…
Browse files Browse the repository at this point in the history
…ects

Call prepare on lists of input objects
  • Loading branch information
rmosolgo committed Apr 25, 2024
2 parents c72f700 + 3027f03 commit 81db09b
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 2 deletions.
19 changes: 17 additions & 2 deletions lib/graphql/schema/argument.rb
Original file line number Diff line number Diff line change
Expand Up @@ -206,8 +206,8 @@ def statically_coercible?
# Used by the runtime.
# @api private
def prepare_value(obj, value, context: nil)
if value.is_a?(GraphQL::Schema::InputObject)
value = value.prepare
if type.unwrap.kind.input_object?
value = recursively_prepare_input_object(value, type)
end

Schema::Validator.validate!(validators, obj, context, value)
Expand Down Expand Up @@ -373,6 +373,21 @@ def initialize(argument)

private

def recursively_prepare_input_object(value, type)
if type.non_null?
type = type.of_type
end

if type.list? && !value.nil?
inner_type = type.of_type
value.map { |v| recursively_prepare_input_object(v, inner_type) }
elsif value.is_a?(GraphQL::Schema::InputObject)
value.prepare
else
value
end
end

def validate_input_type(input_type)
if input_type.is_a?(String) || input_type.is_a?(GraphQL::Schema::LateBoundType)
# Do nothing; assume this will be validated later
Expand Down
24 changes: 24 additions & 0 deletions spec/graphql/schema/input_object_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -420,13 +420,29 @@ def prepare_once(input:)
input.prepared_count
end

field :prepare_list, [Int] do
argument :input, [OnlyOnePrepareInputObject]
end

def prepare_list(input:)
input.map(&:prepared_count)
end

field :prepare_and_load, String do
argument :input, PrepareAndLoadInput
end

def prepare_and_load(input:)
"#{input[:value]}/#{input[:thing][:name]}"
end

field :prepare_list_of_lists, [[Int]] do
argument :input, [[OnlyOnePrepareInputObject]]
end

def prepare_list_of_lists(input:)
input.map { |i| i.map(&:prepared_count) }
end
end

class Schema < GraphQL::Schema
Expand Down Expand Up @@ -462,6 +478,14 @@ def self.object_from_id(id, _ctx)
assert_equal 1, res["data"]["prepareOnce"]
end

it "calls prepare on lists of input objects" do
res = InputObjectPrepareObjectTest::Schema.execute("{ prepareList( input:[{ i: 1 }, { i: 1}]) }")
assert_equal [1, 1], res["data"]["prepareList"]

res = InputObjectPrepareObjectTest::Schema.execute("{ prepareListOfLists( input:[[{ i: 1 }, { i: 1}], [{i: 2}, {i: 2}]]) }")
assert_equal [[1, 1], [1, 1]], res["data"]["prepareListOfLists"]
end

it "calls prepare on the input object (variable)" do
query_str = <<-GRAPHQL
query ($input: RangeInput!){ inputs(input: $input) }
Expand Down

0 comments on commit 81db09b

Please sign in to comment.