How to implement a custom GraphQL::Batch::Loader
mainA loader is a class that inherits from GraphQL::Batch::Loader. It is initialized with arguments used for grouping (e.g., a model class) and must implement a perform method.
In the perform method, you receive an array of keys (IDs). You should use fulfill(key, value) to resolve each key. If a key cannot be resolved, you should still call fulfill(key, nil) to ensure the promise is settled and doesn't hang.
class RecordLoader < GraphQL::Batch::Loader
def initialize(model)
@model = model
end
def perform(ids)
@model.where(id: ids).each { |record| fulfill(record.id, record) }
ids.each { |id| fulfill(id, nil) unless fulfilled?(id) }
end
end