Module: GraphQL::QueryResolver

Defined in:
lib/graphql/query_resolver.rb,
lib/graphql/query_resolver/version.rb

Constant Summary collapse

VERSION =
"0.2.0"

Class Method Summary collapse

Class Method Details

.has_reflection_with_name?(class_name, selection_name) ⇒ Boolean

Returns:

  • (Boolean)


39
40
41
# File 'lib/graphql/query_resolver.rb', line 39

def self.has_reflection_with_name?(class_name, selection_name)
  class_name.reflections.with_indifferent_access[selection_name].present?
end

.map_dependencies(class_name, ast_node, dependencies = {}) ⇒ Object



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/graphql/query_resolver.rb', line 43

def self.map_dependencies(class_name, ast_node, dependencies={})
  ast_node.selections.each do |selection|
    name = selection.name

    if using_relay_pagination?(selection)
      map_relay_pagination_depencies(class_name, selection, dependencies)
      next
    end

    if has_reflection_with_name?(class_name, name)
      begin
        current_class_name = selection.name.singularize.classify.constantize
        dependencies[name] = map_dependencies(current_class_name, selection)
      rescue NameError
        selection_name = class_name.reflections.with_indifferent_access[selection.name].options[:class_name]
        current_class_name = selection_name.singularize.classify.constantize
        dependencies[selection.name.to_sym] = map_dependencies(current_class_name, selection)
        next
      end
    end
  end

  dependencies
end

.map_relay_pagination_depencies(class_name, selection, dependencies) ⇒ Object



29
30
31
32
33
34
35
36
37
# File 'lib/graphql/query_resolver.rb', line 29

def self.map_relay_pagination_depencies(class_name, selection, dependencies)
  node_selection = selection.selections.find { |sel| sel.name == 'node' }

  if node_selection.present?
    map_dependencies(class_name, node_selection, dependencies)
  else
    dependencies
  end
end

.run(model_class, context, return_type) ⇒ Object



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/graphql/query_resolver.rb', line 7

def self.run(model_class, context, return_type)
  to_load = yield
  dependencies = {}

  reflection_dependencies = map_dependencies(model_class, context.ast_node)
  dependencies = reflection_dependencies.merge(dependencies)

  if dependencies.any? && to_load.present?
    if ActiveRecord::VERSION::MAJOR < 4
      ActiveRecord::Associations::Preloader.new(to_load, dependencies).run
    else
      ActiveRecord::Associations::Preloader.new.preload(to_load, dependencies)
    end
  end

  to_load
end

.using_relay_pagination?(selection) ⇒ Boolean

Returns:

  • (Boolean)


25
26
27
# File 'lib/graphql/query_resolver.rb', line 25

def self.using_relay_pagination?(selection)
  selection.name == 'edges'
end