Skip to content

Commit e8148d8

Browse files
committed
Describe how to use a simple preload: helper with GraphQL
1 parent d962df7 commit e8148d8

File tree

1 file changed

+33
-1
lines changed

1 file changed

+33
-1
lines changed

README.md

Lines changed: 33 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -312,7 +312,39 @@ class MyProjectSchema < GraphQL::Schema
312312
end
313313
```
314314

315-
That's it.
315+
---
316+
317+
If you need to use BatchLoader with ActiveRecord in multiple places, you can use this `preload:` helper shared by [Aha!](https://www.aha.io/engineering/articles/automatically-avoiding-graphql-n-1s):
318+
319+
```rb
320+
field :user, UserType, null: false, preload: :user
321+
# ^^^^^^^^^^^^^^
322+
# Simply add this instead of defining custom `user` method with BatchLoader
323+
```
324+
325+
And add this custom field resolver that uses ActiveRecord's preload functionality with BatchLoader:
326+
327+
```rb
328+
# app/graphql/types/base_object.rb
329+
field_class Types::PreloadableField
330+
331+
# app/graphql/types/preloadable_field.rb
332+
class Types::PreloadableField < Types::BaseField
333+
def initialize(*args, preload: nil, **kwargs, &block)
334+
@preloads = preload
335+
super(*args, **kwargs, &block)
336+
end
337+
338+
def resolve(type, args, ctx)
339+
return super unless @preloads
340+
341+
BatchLoader::GraphQL.for(type).batch(key: self) do |records, loader|
342+
ActiveRecord::Associations::Preloader.new.preload(records.map(&:object), @preloads)
343+
records.each { |r| loader.call(r, super(r, args, ctx)) }
344+
end
345+
end
346+
end
347+
```
316348

317349
### Loading multiple items
318350

0 commit comments

Comments
 (0)