Class: GraphQL::Preload::Instrument

Inherits:
Object
  • Object
show all
Defined in:
lib/graphql/preload/instrument.rb

Overview

Provides an instrument for the GraphQL::Field :preload definition

Instance Method Summary collapse

Instance Method Details

#instrument(_type, field) ⇒ Object


5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/graphql/preload/instrument.rb', line 5

def instrument(_type, field)
   = (field)
  return field if .fetch(:preload, nil).nil?

  old_resolver = field.resolve_proc
  new_resolver = ->(obj, args, ctx) do
    return old_resolver.call(obj, args, ctx) unless obj

    if [:preload_scope]
      scope = [:preload_scope].call(args, ctx)
    end

    is_graphql_object = obj.is_a?(GraphQL::Schema::Object)
    respond_to_object = obj.respond_to?(:object)
    record = is_graphql_object && respond_to_object ? obj.object : obj

    preload(record, [:preload], scope).then do
      old_resolver.call(obj, args, ctx)
    end
  end

  field.redefine do
    resolve(new_resolver)
  end
end