Class: GraphQL::ActiveRecordBatcher::FieldInstrumenter

Inherits:
Object
  • Object
show all
Defined in:
lib/graphql/active_record_batcher/field_instrumenter.rb

Instance Method Summary collapse

Instance Method Details

#instrument(type, field) ⇒ Object



4
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
30
31
32
# File 'lib/graphql/active_record_batcher/field_instrumenter.rb', line 4

def instrument(type, field)
  associations = field.[:preloads]

  if associations
    # Model is needed to preload an association
    unless model = type.[:model]
      message = "No ActiveRecord Model set on type #{type.name}'s metadata."\
        " Use `model(YourActiveRecordModel)` inside the type's definition"
      raise StandardError, message
    end

    # Make sure the association exists on the model
    validate(model, associations)

    # "Wrap" the resolve proc with our own, which returns a promise
    old_resolve_proc = field.resolve_proc
    new_resolve_proc = ->(obj, args, ctx) do
      build_preload_promise(obj, model, associations).then do
        old_resolve_proc.call(obj, args, ctx)
      end
    end

    field.redefine do
      resolve(new_resolve_proc)
    end
  else
    field
  end
end