Module: ApolloFederation::EntitiesField

Defined in:
lib/apollo-federation/entities_field.rb

Defined Under Namespace

Modules: ClassMethods

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(base) ⇒ Object



8
9
10
# File 'lib/apollo-federation/entities_field.rb', line 8

def self.included(base)
  base.extend(ClassMethods)
end

Instance Method Details

#_entities(representations:) ⇒ Object



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
# File 'lib/apollo-federation/entities_field.rb', line 29

def _entities(representations:)
  final_result = Array.new(representations.size)
  grouped_references_with_indices =
    representations
    .map
    .with_index { |r, i| [r, i] }
    .group_by { |(r, _i)| r[:__typename] }

  maybe_lazies = grouped_references_with_indices.map do |typename, references_with_indices|
    references = references_with_indices.map(&:first)
    indices = references_with_indices.map(&:last)

    # TODO: Use warden or schema?
    type = context.warden.get_type(typename)
    if type.nil? || type.kind != GraphQL::TypeKinds::OBJECT
      # TODO: Raise a specific error class?
      raise "The _entities resolver tried to load an entity for type \"#{typename}\"," \
            ' but no object type of that name was found in the schema'
    end

    # TODO: What if the type is an interface?
    type_class = class_of_type(type)

    if type_class.underscore_reference_keys
      references.map! do |reference|
        reference.transform_keys do |key|
          GraphQL::Schema::Member::BuildType.underscore(key.to_s).to_sym
        end
      end
    end

    if type_class.respond_to?(:resolve_references)
      results = type_class.resolve_references(references, context)
    elsif type_class.respond_to?(:resolve_reference)
      results = references.map { |reference| type_class.resolve_reference(reference, context) }
    else
      results = references
    end

    context.schema.after_lazy(results) do |resolved_results|
      resolved_results.zip(indices).each do |result, i|
        final_result[i] = context.schema.after_lazy(result) do |resolved_value|
          # TODO: This isn't 100% correct: if (for some reason) 2 different resolve_reference
          # calls return the same object, it might not have the right type
          # Right now, apollo-federation just adds a __typename property to the result,
          # but I don't really like the idea of modifying the resolved object
          context[resolved_value] = type
          resolved_value
        end
      end
    end
  end

  # Make sure we've resolved the outer level of lazies so we can return an array with a possibly lazy
  # entry for each requested entity
  GraphQL::Execution::Lazy.all(maybe_lazies).then do
    final_result
  end
end