Sha256: 2e2eb572b8bad6b0257baf3c87ca04b13348bb643ad04e875d3c17c3e27c9a71

Contents?: true

Size: 1.31 KB

Versions: 6

Compression:

Stored size: 1.31 KB

Contents

require 'graphql/result_cache/condition'
require 'graphql/result_cache/context_config'
require 'graphql/result_cache/key'
require 'graphql/result_cache/callback'

module GraphQL
  module ResultCache
    class FieldInstrument
      def instrument _type, field
        return field unless field.metadata[:result_cache]

        cached_resolve_proc = cached_resolve(field)
        field.redefine do
          resolve(cached_resolve_proc)
          type(field.type.of_type) if field.type.non_null?
        end
      end

      private

      def cached_resolve field
        old_resolve_proc = field.resolve_proc
        cache_config = field.metadata[:result_cache]
        cache_config = {} unless cache_config.is_a?(Hash)
        lambda do |obj, args, ctx|
          if Condition.new(cache_config, obj: obj, args: args, ctx: ctx).true?
            ctx[:result_cache] ||= ContextConfig.new
            cache_key = Key.new(obj: obj, args: args, ctx: ctx, key: cache_config[:key])
            after_process = Callback.new(obj: obj, args: args, ctx: ctx, value: cache_config[:after_process]) if cache_config[:after_process]
            cached = ctx[:result_cache].add context: ctx, key: cache_key.to_s, after_process: after_process
          end
          old_resolve_proc.call(obj, args, ctx) unless cached
        end
      end
    end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
graphql-result_cache-0.1.8 lib/graphql/result_cache/field_instrument.rb
graphql-result_cache-0.1.7 lib/graphql/result_cache/field_instrument.rb
graphql-result_cache-0.1.6 lib/graphql/result_cache/field_instrument.rb
graphql-result_cache-0.1.5 lib/graphql/result_cache/field_instrument.rb
graphql-result_cache-0.1.4 lib/graphql/result_cache/field_instrument.rb
graphql-result_cache-0.1.3 lib/graphql/result_cache/field_instrument.rb