Skip to content
This repository was archived by the owner on Oct 26, 2022. It is now read-only.

Commit 7768b59

Browse files
Pass context through to key generation proc
[resolve #49]
1 parent 8c7e486 commit 7768b59

3 files changed

Lines changed: 11 additions & 6 deletions

File tree

lib/graphql/cache/fetcher.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ def cached_resolve(type, field)
3030
old_resolve_proc = field.resolve_proc
3131

3232
lambda do |obj, args, ctx|
33-
key = cache_key(obj, args, type, field)
33+
key = cache_key(obj, args, type, field, ctx)
3434

3535
value = Marshal[key].read(
3636
field.metadata[:cache], force: ctx[:force_cache]

lib/graphql/cache/key.rb

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,9 @@ class Key
1515
# The graphql field being resolved
1616
attr_accessor :field
1717

18+
# The current graphql query context
19+
attr_accessor :context
20+
1821
# Metadata passed to the cache key on field definition
1922
attr_accessor :metadata
2023

@@ -24,11 +27,12 @@ class Key
2427
# @param args [GraphQL::Arguments] The internal graphql-ruby wrapper for field arguments
2528
# @param type [GraphQL::Schema::Type] The type definition of the parent object
2629
# @param field [GraphQL::Schema::Field] The field being resolved
27-
def initialize(obj, args, type, field)
30+
def initialize(obj, args, type, field, context = {})
2831
@object = obj.object
2932
@arguments = args
3033
@type = type
3134
@field = field
35+
@context = context
3236
@metadata = field.metadata[:cache]
3337

3438
@metadata = { cache: @metadata } unless @metadata.is_a?(Hash)
@@ -80,7 +84,7 @@ def object_identifier
8084
when Symbol
8185
object.send(metadata[:key])
8286
when Proc
83-
metadata[:key].call(object)
87+
metadata[:key].call(object, context)
8488
when NilClass
8589
guess_id
8690
else
@@ -93,6 +97,7 @@ def guess_id
9397
return object.cache_key_with_version if object.respond_to?(:cache_key_with_version)
9498
return object.cache_key if object.respond_to?(:cache_key)
9599
return object.id if object.respond_to?(:id)
100+
96101
object.object_id
97102
end
98103
end

spec/graphql/cache/key_spec.rb

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -72,15 +72,15 @@ module Cache
7272

7373
context 'when metadata key is a proc' do
7474
let(:key_proc) do
75-
-> (obj) { 'baz' }
75+
-> (obj, ctx) { 'baz' }
7676
end
7777

7878
before do
7979
field.metadata[:cache] = { key: key_proc }
8080
end
8181

82-
it 'calls the proc passing object' do
83-
expect(key_proc).to receive(:call).and_call_original
82+
it 'calls the proc passing object and query context' do
83+
expect(key_proc).to receive(:call).with(obj, {}).and_call_original
8484
subject.object_identifier
8585
end
8686
end

0 commit comments

Comments
 (0)