Class: Graphql::EagerLoader::LookaheadLoader

Inherits:
Object
  • Object
show all
Defined in:
lib/graphql/eager_loader/lookahead_loader.rb

Class Method Summary collapse

Class Method Details

.associations(model_class, lookahead) ⇒ Object



19
20
21
22
23
24
25
# File 'lib/graphql/eager_loader/lookahead_loader.rb', line 19

def self.associations(model_class, lookahead)
  self.selections(lookahead).map(&:name).map(&:to_s).map do |selection|
    model_class.reflections.find do |name, _association|
      name == selection
    end
  end.compact.to_h
end

.call(model_class, lookahead, &block) ⇒ Object

Call this method like this: Graphql::EagerLoader::LookaheadLoader.call(Project, lookahead)

Here’s a full example with ‘graphql’ field:

field :projects, Types::ProjectType, null: true, extras: [:lookahead] def projects(lookahead:)

Graphql::EagerLoader::LookaheadLoader.call(Project, lookahead).all # or: .where(published: true)

end



14
15
16
17
# File 'lib/graphql/eager_loader/lookahead_loader.rb', line 14

def self.call(model_class, lookahead, &block)
  associations = self.associations(model_class, lookahead)
  eager_load_associations(model_class, associations, &block)
end

.eager_load_associations(model_class, associations, &block) ⇒ Object

This method allows you to add additional functionality while eager loading app’s models. For example you can do stuff like (notice the location of .all below):

field :projects, Types::ProjectType, null: true, extras: [:lookahead] def projects(lookahead:)

Graphql::EagerLoader::LookaheadLoader.call(Project, lookahead) do |eager_loaded_model, associations|
  associations.values.each do |association|
    if association.instance_of?(ActiveRecord::Reflection::HasManyReflection)
      eager_loaded_model = eager_loaded_model.merge(association.klass.where(published: true))
    end
  end
  eager_loaded_model
end.all

end



50
51
52
53
54
55
56
57
58
# File 'lib/graphql/eager_loader/lookahead_loader.rb', line 50

def self.eager_load_associations(model_class, associations, &block)
  return model_class if associations.blank?

  eager_loaded_model = model_class.eager_load(*associations.keys)

  eager_loaded_model = yield eager_loaded_model, associations if block_given?

  eager_loaded_model
end

.selections(lookahead) ⇒ Object



27
28
29
30
31
32
33
34
# File 'lib/graphql/eager_loader/lookahead_loader.rb', line 27

def self.selections(lookahead)
  selection_names = lookahead.selections.map(&:name)
  if selection_names == %i[edges nodes] || selection_names == [:nodes]
    lookahead.selections.find { |lookahead| lookahead.name == :nodes }.selections
  else
    lookahead.selections
  end
end