Skip to content

Commit da8b66b

Browse files
committed
Fix sequential mutations with Dataloader
1 parent 882c709 commit da8b66b

File tree

2 files changed

+32
-0
lines changed

2 files changed

+32
-0
lines changed

lib/graphql/execution/interpreter/runtime.rb

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -393,6 +393,12 @@ def evaluate_selections(owner_object, owner_type, is_eager_selection, gathered_s
393393
selections_result.merge_into(target_result)
394394
end
395395
}
396+
# Field resolution may pause the fiber,
397+
# so it wouldn't get to the `Resolve` call that happens below.
398+
# So instead trigger a run from this outer context.
399+
if is_eager_selection
400+
@dataloader.run
401+
end
396402
end
397403

398404
selections_result

spec/graphql/dataloader_spec.rb

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -319,9 +319,23 @@ def resolve(argument_2:)
319319
end
320320
end
321321

322+
class Mutation3 < GraphQL::Schema::Mutation
323+
argument :label, String
324+
type String
325+
326+
def resolve(label:)
327+
log = context[:mutation_log] ||= []
328+
log << "begin #{label}"
329+
dataloader.with(DataObject).load(1)
330+
log << "end #{label}"
331+
label
332+
end
333+
end
334+
322335
class Mutation < GraphQL::Schema::Object
323336
field :mutation_1, mutation: Mutation1
324337
field :mutation_2, mutation: Mutation2
338+
field :mutation_3, mutation: Mutation3
325339
end
326340

327341
mutation(Mutation)
@@ -403,6 +417,18 @@ def self.included(child_class)
403417
assert_equal [[:mget, ["5", "6"]], [:mget, ["2", "3"]]], database_log
404418
end
405419

420+
it "runs mutations sequentially" do
421+
res = schema.execute <<-GRAPHQL
422+
mutation {
423+
first: mutation3(label: "first")
424+
second: mutation3(label: "second")
425+
}
426+
GRAPHQL
427+
428+
assert_equal({ "first" => "first", "second" => "second" }, res["data"])
429+
assert_equal ["begin first", "end first", "begin second", "end second"], res.context[:mutation_log]
430+
end
431+
406432
it "batch-loads" do
407433
res = schema.execute <<-GRAPHQL
408434
{

0 commit comments

Comments
 (0)