@@ -258,4 +258,75 @@ def resolve(**inputs)
258258 res = schema . execute ( "mutation { child(thingName: \" abc\" , thingId: \" 123\" ) { inputs } }" )
259259 assert_equal "{:thing_id=>\" 123\" , :thing_name=>\" abc\" }" , res [ "data" ] [ "child" ] [ "inputs" ]
260260 end
261+
262+ describe "flushing dataloader cache" do
263+ class MutationDataloaderCacheSchema < GraphQL ::Schema
264+ module Database
265+ DATA = { }
266+ def self . get ( id )
267+ value = DATA [ id ] ||= 0
268+ OpenStruct . new ( id : id , value : value )
269+ end
270+
271+ def self . increment ( id )
272+ DATA [ id ] ||= 0
273+ DATA [ id ] += 1
274+ end
275+
276+ def self . clear
277+ DATA . clear
278+ end
279+ end
280+
281+ class CounterSource < GraphQL ::Dataloader ::Source
282+ def fetch ( ids )
283+ ids . map { |id | Database . get ( id ) }
284+ end
285+ end
286+ class CounterType < GraphQL ::Schema ::Object
287+ def self . authorized? ( obj , ctx )
288+ # Just force the load here, too:
289+ ctx . dataloader . with ( CounterSource ) . load ( obj . id )
290+ true
291+ end
292+ field :value , Integer
293+ end
294+ class Increment < GraphQL ::Schema ::Mutation
295+ field :counter , CounterType
296+ argument :counter_id , ID , loads : CounterType
297+
298+ def resolve ( counter :)
299+ Database . increment ( counter . id )
300+ {
301+ counter : dataloader . with ( CounterSource ) . load ( counter . id )
302+ }
303+ end
304+ end
305+
306+ class Mutation < GraphQL ::Schema ::Object
307+ field :increment , mutation : Increment
308+ end
309+
310+ mutation ( Mutation )
311+
312+ def self . object_from_id ( id , ctx )
313+ ctx . dataloader . with ( CounterSource ) . load ( id )
314+ end
315+
316+ def self . resolve_type ( abs_type , obj , ctx )
317+ CounterType
318+ end
319+
320+ use GraphQL ::Dataloader
321+ end
322+
323+ it "clears the cache after authorized and loads" do
324+ MutationDataloaderCacheSchema ::Database . clear
325+ res = MutationDataloaderCacheSchema . execute ( "mutation { increment(counterId: \" 4\" ) { counter { value } } }" )
326+ assert_equal 1 , res [ "data" ] [ "increment" ] [ "counter" ] [ "value" ]
327+
328+ res2 = MutationDataloaderCacheSchema . execute ( "mutation { increment(counterId: \" 4\" ) { counter { value } } }" )
329+ assert_equal 2 , res2 [ "data" ] [ "increment" ] [ "counter" ] [ "value" ]
330+ end
331+ end
261332end
0 commit comments