Class: Desiru::GraphQL::DataLoader

Inherits:
Object
  • Object
show all
Defined in:
lib/desiru/graphql/data_loader.rb

Overview

DataLoader pattern implementation for batching Desiru module calls Prevents N+1 query problems when multiple GraphQL fields request similar data

Defined Under Namespace

Classes: BatchLoader, Promise

Instance Method Summary collapse

Constructor Details

#initializeDataLoader

Returns a new instance of DataLoader.



8
9
10
11
12
13
14
# File 'lib/desiru/graphql/data_loader.rb', line 8

def initialize
  @loaders = {}
  @results_cache = {}
  @pending_loads = Hash.new { |h, k| h[k] = [] }
  @pending_promises = Hash.new { |h, k| h[k] = {} }
  @mutex = Mutex.new
end

Instance Method Details

#clear!Object

Clear all caches



37
38
39
40
41
42
43
44
# File 'lib/desiru/graphql/data_loader.rb', line 37

def clear!
  @mutex.synchronize do
    @results_cache.clear
    @pending_loads.clear
    @pending_promises.clear
    @loaders.each_value(&:clear_cache!)
  end
end

#for(module_class_or_instance, **options) ⇒ Object

Get or create a loader for a specific module



17
18
19
20
21
22
# File 'lib/desiru/graphql/data_loader.rb', line 17

def for(module_class_or_instance, **options)
  # Handle both module classes and instances
  module_class = module_class_or_instance.is_a?(Class) ? module_class_or_instance : module_class_or_instance.class
  key = loader_key(module_class, options)
  @loaders[key] ||= BatchLoader.new(module_class_or_instance, self, **options)
end

#perform_loadsObject

Execute all pending loads in batch



25
26
27
28
29
30
31
32
33
34
# File 'lib/desiru/graphql/data_loader.rb', line 25

def perform_loads
  @mutex.synchronize do
    @pending_loads.each do |loader_key, batch|
      process_loader_batch(loader_key, batch)
    end

    @pending_loads.clear
    @pending_promises.clear
  end
end