Class: Gitlab::Graphql::Loaders::BatchModelLoader

Inherits:
Object
  • Object
show all
Defined in:
lib/gitlab/graphql/loaders/batch_model_loader.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(model_class, model_id, preloads = nil) ⇒ BatchModelLoader

Returns a new instance of BatchModelLoader.



9
10
11
12
13
# File 'lib/gitlab/graphql/loaders/batch_model_loader.rb', line 9

def initialize(model_class, model_id, preloads = nil)
  @model_class = model_class
  @model_id = model_id
  @preloads = preloads || []
end

Instance Attribute Details

#model_classObject (readonly)

Returns the value of attribute model_class.



7
8
9
# File 'lib/gitlab/graphql/loaders/batch_model_loader.rb', line 7

def model_class
  @model_class
end

#model_idObject (readonly)

Returns the value of attribute model_id.



7
8
9
# File 'lib/gitlab/graphql/loaders/batch_model_loader.rb', line 7

def model_id
  @model_id
end

#preloadsObject (readonly)

Returns the value of attribute preloads.



7
8
9
# File 'lib/gitlab/graphql/loaders/batch_model_loader.rb', line 7

def preloads
  @preloads
end

Instance Method Details

#findObject

rubocop: disable CodeReuse/ActiveRecord



16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/gitlab/graphql/loaders/batch_model_loader.rb', line 16

def find
  BatchLoader::GraphQL.for([model_id.to_i, preloads]).batch(key: model_class) do |for_params, loader, args|
    model = args[:key]
    keys_by_id = for_params.group_by(&:first)
    ids = for_params.map(&:first)
    preloads = for_params.flat_map(&:second).uniq
    results = model.where(id: ids)
    results = results.preload(*preloads) unless preloads.empty?

    results.each do |record|
      keys_by_id.fetch(record.id, []).each { |k| loader.call(k, record) }
    end
  end
end