Class: GraphitiGql::Loaders::BelongsTo
- Inherits:
-
GraphQL::Batch::Loader
- Object
- GraphQL::Batch::Loader
- GraphitiGql::Loaders::BelongsTo
- Defined in:
- lib/graphiti_gql/loaders/belongs_to.rb
Instance Method Summary collapse
-
#initialize(sideload, params) ⇒ BelongsTo
constructor
A new instance of BelongsTo.
- #perform(ids) ⇒ Object
Constructor Details
#initialize(sideload, params) ⇒ BelongsTo
Returns a new instance of BelongsTo.
11 12 13 14 |
# File 'lib/graphiti_gql/loaders/belongs_to.rb', line 11 def initialize(sideload, params) @sideload = sideload @params = params end |
Instance Method Details
#perform(ids) ⇒ Object
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 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 |
# File 'lib/graphiti_gql/loaders/belongs_to.rb', line 16 def perform(ids) Graphiti.broadcast("association", { sideload: @sideload }) # process nils ids.each { |id| fulfill(id, nil) if id.nil? } ids.compact! return if ids.empty? if @params[:simpleid] && !to_polymorphic_resource? if @sideload.type == :polymorphic_belongs_to ids.each do |id| child = @sideload.children.values.find { |c| c.group_name == id[:type].to_sym } type = Schema::Registry.instance.get(child.resource.class, interface: false)[:type] fulfill(id, FakeRecord.new(id[:id], type, child.resource)) end else type = Schema::Registry.instance.get(@sideload.resource.class)[:type] ids.each { |id| fulfill(id, FakeRecord.new(id, type, @sideload.resource)) } end return end if @sideload.type == :polymorphic_belongs_to groups = ids.group_by { |hash| hash[:type] } payload = {} groups.each_pair do |key, val| payload[key] = val.map { |v| v[:id] } end futures = [] payload.each_pair do |key, value| params = { filter: {} } klass = @sideload.children.values.find { |c| c.group_name == key.to_sym } filter_ids = value.map { |id| @sideload.resource.class.gid(id.to_s) } params = @params.merge({ filter: { id: { eq: filter_ids } } }) futures << Concurrent::Future.execute do { type: key, data: klass.resource.class.all(params).data } end end values = futures.map(&:value) ids.each do |id| records_for_type = values.find { |v| v[:type] == id[:type] } corresponding = records_for_type[:data].find { |r| r.id == id[:id] } fulfill(id, corresponding) end else resource = Schema.registry.get(@sideload.resource.class)[:resource] params = @params.deep_dup unless resource.singular filter_ids = ids.map { |id| @sideload.resource.class.gid(id.to_s) } params[:filter] = {id: { eq: filter_ids } } end records = resource.all(params).data if resource.singular ids.each { |id| fulfill(id, records[0]) } else map = records.index_by { |record| record.id } ids.each { |id| fulfill(id, map[id]) } end end end |