Provides an executor for the graphql gem which allows queries to be batched.
Add this line to your application's Gemfile:
gem'graphql-batch'And then execute:
$ bundle
Or install it yourself as:
$ gem install graphql-batch
Require the library
require'graphql/batch'Define a custom loader, which is initialized with arguments that are used for grouping and a perform method for performing the batch load.
classRecordLoader < GraphQL::Batch::Loaderdefinitialize(model)@model=modelenddefperform(ids)@model.where(id: ids).each{ |record| fulfill(record.id,record)}ids.each{ |id| fulfill(id,nil)unlessfulfilled?(id)}endendUse GraphQL::Batch as a plugin in your schema after specifying the mutation
so that GraphQL::Batch can extend the mutation fields to clear the cache after
they are resolved.
classMySchema < GraphQL::SchemaqueryMyQueryTypemutationMyMutationTypeuseGraphQL::BatchendThe loader class can be used from the resolver for a graphql field by calling .for with the grouping arguments to get a loader instance, then call .load on that instance with the key to load.
field:product,Types::Product,null: truedoargument:id,ID,required: trueenddefproduct(id:)RecordLoader.for(Product).load(id)endThe loader also supports batch loading an array of records instead of just a single record, via load_many. For example:
field:products,[Types::Product,null: true],null: falsedoargument:ids,[ID],required: trueenddefproducts(ids:)RecordLoader.for(Product).load_many(ids)endAlthough this library doesn't have a dependency on active record, the examples directory has record and association loaders for active record which handles edge cases like type casting ids and overriding GraphQL::Batch::Loader#cache_key to load associations on records with the same id.
GraphQL::Batch::Loader#load returns a Promise using the promise.rb gem to provide a promise based API, so you can transform the query results using .then
defproduct_title(id:)RecordLoader.for(Product).load(id).thendo |product|
product.titleendendYou may also need to do another query that depends on the first one to get the result, in which case the query block can return another query.
defproduct_image(id:)RecordLoader.for(Product).load(id).thendo |product|
RecordLoader.for(Image).load(product.image_id)endendIf the second query doesn't depend on the first one, then you can use Promise.all, which allows each query in the group to be batched with other queries.
defall_collectionsPromise.all([CountLoader.for(Shop,:smart_collections).load(context.shop_id),CountLoader.for(Shop,:custom_collections).load(context.shop_id),]).then(&:sum)end.then can optionally take two lambda arguments, the first of which is equivalent to passing a block to .then, and the second one handles exceptions. This can be used to provide a fallback
defproduct(id:)# Try the cache first ...CacheLoader.for(Product).load(id).then(nil,lambdado |exc|
# But if there's a connection error, go to the underlying databaseraiseexcunlessexc.is_a?(Redis::BaseConnectionError)logger.warnerr.messageRecordLoader.for(Product).load(id)end)endYou can prime the loader cache with a specific value, which can be useful in certain situations.
defliked_productsliked_products=Product.where(liked: true).loadliked_products.eachdo |product|
RecordLoader.for(Product).prime(product.id,product)endendPriming will add key/value to the loader cache only if it didn't exist before.
Your loaders can be tested outside of a GraphQL query by doing the
batch loads in a block passed to GraphQL::Batch.batch. That method
will set up thread-local state to store the loaders, batch load any
promise returned from the block then clear the thread-local state
to avoid leaking state between tests.
deftest_single_queryproduct=products(:snowboard)title=GraphQL::Batch.batchdoRecordLoader.for(Product).load(product.id).then(&:title)endassert_equalproduct.title,titleendAfter checking out the repo, run bin/setup to install dependencies. Then, run rake test to run the tests. You can also run bin/console for an interactive prompt that will allow you to experiment.
See our contributing guidelines for more information.
The gem is available as open source under the terms of the MIT License.