2024-04-29 00:17:15 +02:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
2018-11-20 22:27:40 +01:00
|
|
|
# references:
|
|
|
|
# https://github.com/Shopify/graphql-batch/blob/master/examples/record_loader.rb
|
|
|
|
|
|
|
|
module Loaders
|
|
|
|
class Record < GraphQL::Batch::Loader
|
2021-01-28 13:53:01 +01:00
|
|
|
def initialize(model, column: model.primary_key, where: nil, includes: nil, array: false)
|
2018-11-20 22:27:40 +01:00
|
|
|
@model = model
|
|
|
|
@column = column.to_s
|
|
|
|
@column_type = model.type_for_attribute(@column)
|
|
|
|
@where = where
|
2021-01-28 13:53:01 +01:00
|
|
|
@includes = includes
|
|
|
|
@array = array
|
2018-11-20 22:27:40 +01:00
|
|
|
end
|
|
|
|
|
|
|
|
def load(key)
|
|
|
|
super(@column_type.cast(key))
|
|
|
|
end
|
|
|
|
|
|
|
|
def perform(keys)
|
2021-01-28 13:53:01 +01:00
|
|
|
query(keys).each do |record|
|
|
|
|
fulfilled_value = @array ? [record].compact : record
|
|
|
|
fulfill(record.public_send(@column), fulfilled_value)
|
|
|
|
end
|
2023-04-18 09:31:17 +02:00
|
|
|
keys.each { |key| fulfill(key, @array ? [] : nil) unless fulfilled?(key) }
|
2018-11-20 22:27:40 +01:00
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
|
|
|
|
def query(keys)
|
|
|
|
scope = @model
|
|
|
|
scope = scope.where(@where) if @where
|
2021-01-28 13:53:01 +01:00
|
|
|
scope = scope.includes(@includes) if @includes
|
2018-11-20 22:27:40 +01:00
|
|
|
scope.where(@column => keys)
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|