Module: GraphQL::Schema::Member::HasDataloader

Included in:
Interface::DefinitionMethods, Object, Resolver
Defined in:
lib/graphql/schema/member/has_dataloader.rb

Overview

Shared methods for working with Dataloader inside GraphQL runtime objects.

Instance Method Summary collapse

Instance Method Details

#dataload(source_class, *source_args, load_key) ⇒ Object

A shortcut method for loading a key from a source. Identical to dataloader.with(source_class, *source_args).load(load_key)



19
20
21
# File 'lib/graphql/schema/member/has_dataloader.rb', line 19

def dataload(source_class, *source_args, load_key)
  dataloader.with(source_class, *source_args).load(load_key)
end

#dataload_association(record = object, association_name, scope: nil) ⇒ ActiveRecord::Base?

Look up an associated record using a Rails association (via Dataloader::ActiveRecordAssociationSource)

Examples:

Looking up a belongs_to on the current object

dataload_association(:parent) # Equivalent to `object.parent`, but dataloaded

Looking up an associated record on some other object

dataload_association(comment, :post) # Equivalent to `comment.post`, but dataloaded


51
52
53
54
55
56
57
58
# File 'lib/graphql/schema/member/has_dataloader.rb', line 51

def dataload_association(record = object, association_name, scope: nil)
  source = if scope
    dataloader.with(Dataloader::ActiveRecordAssociationSource, association_name, scope)
  else
    dataloader.with(Dataloader::ActiveRecordAssociationSource, association_name)
  end
  source.load(record)
end

#dataload_record(model, find_by_value, find_by: nil) ⇒ ActiveRecord::Base?

Find an object with ActiveRecord via Dataloader::ActiveRecordSource.

Examples:

Finding a record by ID

dataload_record(Post, 5) # Like `Post.find(5)`, but dataloaded

Finding a record by another attribute

dataload_record(User, "matz", find_by: :handle) # Like `User.find_by(handle: "matz")`, but dataloaded


32
33
34
35
36
37
38
39
40
# File 'lib/graphql/schema/member/has_dataloader.rb', line 32

def dataload_record(model, find_by_value, find_by: nil)
  source = if find_by
    dataloader.with(Dataloader::ActiveRecordSource, model, find_by: find_by)
  else
    dataloader.with(Dataloader::ActiveRecordSource, model)
  end

  source.load(find_by_value)
end

#dataloaderGraphQL::Dataloader

Returns The dataloader for the currently-running query.



10
11
12
# File 'lib/graphql/schema/member/has_dataloader.rb', line 10

def dataloader
  context.dataloader
end