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
33
34
35
# File 'lib/graphql/active_record_batcher/field_instrumenter.rb', line 4

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

  if association_to_preload
    # 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_preload(model, association_to_preload)

    loader = GraphQL::ActiveRecordBatcher::AssociationLoader.new(
      model,
      association_to_preload
    )

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

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