Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

GraphQL::Extras::PreloadDefault: preload associations by default #4

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 39 additions & 0 deletions lib/graphql/extras/preload.rb
Original file line number Diff line number Diff line change
Expand Up @@ -29,5 +29,44 @@ def resolve(object, args, context)
super
end
end

module PreloadDefault
# @override
def initialize(*args, preload: nil, **opts, &block)
@preload = preload
if maybe_preload(opts[:type])
@preload_by_name = opts[:name]&.to_s
end
super(*args, **opts, &block)
end

# @override
def resolve(object, args, context)
if @preload == false
# nop
elsif @preload
loader = context.dataloader.with(PreloadSource, @preload)
loader.load(object.object)
elsif @preload_by_name && object.object.class.respond_to?(:reflections) && object.object.class.reflections.key?(@preload_by_name)
loader = context.dataloader.with(PreloadSource, @preload_by_name)
loader.load(object.object)
end

super
end

private

def maybe_preload(type)
(
type.is_a?(Array) &&
type.first.is_a?(Class) &&
type.first < GraphQL::Schema::Object
) || (
type.is_a?(Class) &&
type < GraphQL::Schema::Object
)
end
end
end
end