Class: Desiru::GraphQL::DataLoader
- Inherits:
-
Object
- Object
- Desiru::GraphQL::DataLoader
- 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
-
#clear! ⇒ Object
Clear all caches.
-
#for(module_class_or_instance, **options) ⇒ Object
Get or create a loader for a specific module.
-
#initialize ⇒ DataLoader
constructor
A new instance of DataLoader.
-
#perform_loads ⇒ Object
Execute all pending loads in batch.
Constructor Details
#initialize ⇒ DataLoader
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, **) # 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, ) @loaders[key] ||= BatchLoader.new(module_class_or_instance, self, **) end |
#perform_loads ⇒ Object
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 |