Class: GraphQL::FragmentCache::Fragment

Inherits:
Object
  • Object
show all
Defined in:
lib/graphql/fragment_cache/fragment.rb

Overview

Represents a single fragment to cache

Constant Summary collapse

NIL_IN_CACHE =
Object.new

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(context, **options) ⇒ Fragment

Returns a new instance of Fragment.



41
42
43
44
45
46
# File 'lib/graphql/fragment_cache/fragment.rb', line 41

def initialize(context, **options)
  @context = context
  @keep_in_context = options.delete(:keep_in_context)
  @options = options
  @path = interpreter_context[:current_path]
end

Instance Attribute Details

#contextObject (readonly)

Returns the value of attribute context.



39
40
41
# File 'lib/graphql/fragment_cache/fragment.rb', line 39

def context
  @context
end

#optionsObject (readonly)

Returns the value of attribute options.



39
40
41
# File 'lib/graphql/fragment_cache/fragment.rb', line 39

def options
  @options
end

#pathObject (readonly)

Returns the value of attribute path.



39
40
41
# File 'lib/graphql/fragment_cache/fragment.rb', line 39

def path
  @path
end

Class Method Details

.read_multi(fragments) ⇒ Object



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/graphql/fragment_cache/fragment.rb', line 14

def read_multi(fragments)
  unless FragmentCache.cache_store.respond_to?(:read_multi)
    return fragments.map { |f| [f, f.read] }.to_h
  end

  fragments_to_cache_keys = fragments
    .map { |f| [f, f.cache_key] }.to_h

  # Filter out all the cache_keys for fragments with renew_cache: true in their context
  cache_keys = fragments_to_cache_keys
    .reject { |k, _v| k.context[:renew_cache] == true }.values

  # If there are cache_keys look up values with read_multi otherwise return an empty hash
  cache_keys_to_values = if cache_keys.empty?
    {}
  else
    FragmentCache.cache_store.read_multi(*cache_keys)
  end

  # Fragmenst without values or with renew_cache: true in their context will have nil values like the read method
  fragments_to_cache_keys
    .map { |fragment, cache_key| [fragment, cache_keys_to_values[cache_key]] }.to_h
end

Instance Method Details

#cache_keyObject



55
56
57
# File 'lib/graphql/fragment_cache/fragment.rb', line 55

def cache_key
  @cache_key ||= CacheKeyBuilder.call(path: path, query: context.query, **options)
end

#readObject



48
49
50
51
52
53
# File 'lib/graphql/fragment_cache/fragment.rb', line 48

def read
  return nil if context[:renew_cache] == true
  return read_from_context { value_from_cache } if @keep_in_context

  value_from_cache
end

#valueObject



63
64
65
# File 'lib/graphql/fragment_cache/fragment.rb', line 63

def value
  final_value.dig(*path)
end

#with_final_value?Boolean

Returns:

  • (Boolean)


59
60
61
# File 'lib/graphql/fragment_cache/fragment.rb', line 59

def with_final_value?
  !final_value.nil?
end