Class: GraphitiGql::Schema::Fields::ToOne

Inherits:
Object
  • Object
show all
Defined in:
lib/graphiti_gql/schema/fields/to_one.rb

Instance Method Summary collapse

Constructor Details

#initialize(sideload, sideload_type) ⇒ ToOne

Returns a new instance of ToOne.



5
6
7
8
# File 'lib/graphiti_gql/schema/fields/to_one.rb', line 5

def initialize(sideload, sideload_type)
  @sideload = sideload
  @sideload_type = sideload_type
end

Instance Method Details

#apply(type) ⇒ Object



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
36
37
38
39
40
41
42
43
44
45
# File 'lib/graphiti_gql/schema/fields/to_one.rb', line 10

def apply(type)
  field = type.field @sideload.name,
    @sideload_type,
    null: true,
    extras: [:lookahead]
  _sideload = @sideload
  type.define_method(@sideload.name) do |**arguments|
    Util.is_readable_sideload!(_sideload)

    if _sideload.type == :has_one
      id = object.send(_sideload.primary_key)
      params = { filter: { _sideload.foreign_key => { eq: id } } }

      resource = Schema.registry.get(@sideload.resource.class)[:resource]
      return resource.all(params).data[0]
    end

    lookahead = arguments[:lookahead]
    id = object.send(_sideload.foreign_key)
    if id.nil?
      Loaders::BelongsTo.for(_sideload, {}).load(nil)
    else
      params = Util.params_from_args(arguments)

      if _sideload.type == :polymorphic_belongs_to
        id = { id: id, type: object.send(_sideload.grouper.field_name) }
      end

      selections = lookahead.selections.map(&:name).sort
      if selections == [:id] || selections == [:__typename, :id]
        params[:simpleid] = true
      end
      Loaders::BelongsTo.for(_sideload, params).load(id)
    end
  end
end