2019-02-15 15:39:39 +05:30
|
|
|
# frozen_string_literal: true
|
|
|
|
|
|
|
|
module Gitlab
|
|
|
|
module Graphql
|
|
|
|
module Loaders
|
|
|
|
class BatchModelLoader
|
2022-07-23 23:45:48 +05:30
|
|
|
attr_reader :model_class, :model_id, :preloads
|
2019-02-15 15:39:39 +05:30
|
|
|
|
2022-07-23 23:45:48 +05:30
|
|
|
def initialize(model_class, model_id, preloads = nil)
|
2021-04-29 21:17:54 +05:30
|
|
|
@model_class = model_class
|
|
|
|
@model_id = model_id
|
2022-07-23 23:45:48 +05:30
|
|
|
@preloads = preloads || []
|
2019-02-15 15:39:39 +05:30
|
|
|
end
|
|
|
|
|
|
|
|
# rubocop: disable CodeReuse/ActiveRecord
|
|
|
|
def find
|
2022-07-23 23:45:48 +05:30
|
|
|
BatchLoader::GraphQL.for([model_id.to_i, preloads]).batch(key: model_class) do |for_params, loader, args|
|
2021-01-29 00:20:46 +05:30
|
|
|
model = args[:key]
|
2022-07-23 23:45:48 +05:30
|
|
|
keys_by_id = for_params.group_by(&:first)
|
|
|
|
ids = for_params.map(&:first)
|
|
|
|
preloads = for_params.flat_map(&:second).uniq
|
2021-01-29 00:20:46 +05:30
|
|
|
results = model.where(id: ids)
|
2022-07-23 23:45:48 +05:30
|
|
|
results = results.preload(*preloads) unless preloads.empty?
|
2019-02-15 15:39:39 +05:30
|
|
|
|
2022-07-23 23:45:48 +05:30
|
|
|
results.each do |record|
|
|
|
|
keys_by_id.fetch(record.id, []).each { |k| loader.call(k, record) }
|
|
|
|
end
|
2019-02-15 15:39:39 +05:30
|
|
|
end
|
|
|
|
end
|
|
|
|
# rubocop: enable CodeReuse/ActiveRecord
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|