Class: GraphQL::FragmentCache::FieldExtension

Inherits:
Schema::FieldExtension
  • Object
show all
Defined in:
lib/graphql/fragment_cache/field_extension.rb

Overview

Wraps resolver with cache method

Defined Under Namespace

Modules: Patch

Constant Summary collapse

NOT_RESOLVED =
Object.new

Instance Method Summary collapse

Constructor Details

#initialize(options:, **_rest) ⇒ FieldExtension

Returns a new instance of FieldExtension.



32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/graphql/fragment_cache/field_extension.rb', line 32

def initialize(options:, **_rest)
  @cache_options = GraphQL::FragmentCache.default_options.merge(options || {})
  @cache_options[:default_options_merged] = true

  @context_key = @cache_options.delete(:context_key)
  @cache_key = @cache_options.delete(:cache_key)

  @if = @cache_options.delete(:if)
  @unless = @cache_options.delete(:unless)

  # Make sure we do not modify options, since they're global
  @cache_options.freeze
end

Instance Method Details

#resolve(object:, arguments:, **_options) ⇒ Object



48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
# File 'lib/graphql/fragment_cache/field_extension.rb', line 48

def resolve(object:, arguments:, **_options)
  resolved_value = NOT_RESOLVED

  if @if.is_a?(Proc) && !object.instance_exec(&@if)
    return yield(object, arguments)
  end

  if @if.is_a?(Symbol) && !object.send(@if)
    return yield(object, arguments)
  end

  if @unless.is_a?(Proc) && object.instance_exec(&@unless)
    return yield(object, arguments)
  end

  if @unless.is_a?(Symbol) && object.send(@unless)
    return yield(object, arguments)
  end

  object_for_key = if @context_key
    Array(@context_key).map { |key| object.context[key] }
  elsif @cache_key == :object
    object.object
  elsif @cache_key == :value
    resolved_value = yield(object, arguments)
  elsif @cache_key.is_a?(Proc)
    object.instance_exec(&@cache_key)
  end

  cache_fragment_options = @cache_options.merge(object: object_for_key)

  object.cache_fragment(**cache_fragment_options) do
    (resolved_value == NOT_RESOLVED) ? yield(object, arguments) : resolved_value
  end
end