Skip to content

Commit

Permalink
Describe how to use a simple preload: helper with GraphQL
Browse files Browse the repository at this point in the history
  • Loading branch information
exAspArk committed Aug 2, 2022
1 parent d962df7 commit e8148d8
Showing 1 changed file with 33 additions and 1 deletion.
34 changes: 33 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -312,7 +312,39 @@ class MyProjectSchema < GraphQL::Schema
end
```

That's it.
---

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):

```rb
field :user, UserType, null: false, preload: :user
# ^^^^^^^^^^^^^^
# Simply add this instead of defining custom `user` method with BatchLoader
```

And add this custom field resolver that uses ActiveRecord's preload functionality with BatchLoader:

```rb
# app/graphql/types/base_object.rb
field_class Types::PreloadableField

# app/graphql/types/preloadable_field.rb
class Types::PreloadableField < Types::BaseField
def initialize(*args, preload: nil, **kwargs, &block)
@preloads = preload
super(*args, **kwargs, &block)
end

def resolve(type, args, ctx)
return super unless @preloads

BatchLoader::GraphQL.for(type).batch(key: self) do |records, loader|
ActiveRecord::Associations::Preloader.new.preload(records.map(&:object), @preloads)
records.each { |r| loader.call(r, super(r, args, ctx)) }
end
end
end
```

### Loading multiple items

Expand Down

0 comments on commit e8148d8

Please sign in to comment.