Sha256: 5e237b03d46c537b850429a419270c5261025d0fd22c52f7bd8eb08a26d51d2d

Contents?: true

Size: 1.25 KB

Versions: 6

Compression:

Stored size: 1.25 KB

Contents

class AssociationLoader < GraphQL::Batch::Loader
  def self.validate(model, association_name)
    new(model, association_name)
    nil
  end

  def initialize(model, association_name)
    super()
    @model = model
    @association_name = association_name
    validate
  end

  def load(record)
    raise TypeError, "#{@model} loader can't load association for #{record.class}" unless record.is_a?(@model)
    return Promise.resolve(read_association(record)) if association_loaded?(record)
    super
  end

  # We want to load the associations on all records, even if they have the same id
  def cache_key(record)
    record.object_id
  end

  def perform(records)
    preload_association(records)
    records.each { |record| fulfill(record, read_association(record)) }
  end

  private

  def validate
    unless @model.reflect_on_association(@association_name)
      raise ArgumentError, "No association #{@association_name} on #{@model}"
    end
  end

  def preload_association(records)
    ::ActiveRecord::Associations::Preloader.new(records: records, associations: @association_name).call
  end

  def read_association(record)
    record.public_send(@association_name)
  end

  def association_loaded?(record)
    record.association(@association_name).loaded?
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
graphql-batch-0.6.0 examples/association_loader.rb
graphql-batch-0.5.4 examples/association_loader.rb
graphql-batch-0.5.3 examples/association_loader.rb
graphql-batch-0.5.2 examples/association_loader.rb
graphql-batch-0.5.1 examples/association_loader.rb
graphql-batch-0.5.0 examples/association_loader.rb