All Projects → Shopify → Graphql Batch

Shopify / Graphql Batch

Licence: mit
A query batching executor for the graphql gem

Programming Languages

ruby
36898 projects - #4 most used programming language

Projects that are alternatives of or similar to Graphql Batch

Dataloader
DataLoader is a generic utility to be used as part of your application's data fetching layer to provide a consistent API over various backends and reduce requests to those backends via batching and caching.
Stars: ✭ 11,040 (+848.45%)
Mutual labels:  graphql, batch
Graphql Resolve Batch
A GraphQL batching model which groups execution by GraphQL fields.
Stars: ✭ 251 (-78.44%)
Mutual labels:  graphql, batch
Join Monster Graphql Tools Adapter
Use Join Monster to fetch your data with Apollo Server.
Stars: ✭ 130 (-88.83%)
Mutual labels:  graphql, batch
Java Dataloader
A Java 8 port of Facebook DataLoader
Stars: ✭ 367 (-68.47%)
Mutual labels:  graphql, batch
Dataloader Php
DataLoaderPhp is a generic utility to be used as part of your application's data fetching layer to provide a simplified and consistent API over various remote data sources such as databases or web services via batching and caching.
Stars: ✭ 160 (-86.25%)
Mutual labels:  graphql, batch
Graphql Upload
Middleware and an Upload scalar to add support for GraphQL multipart requests (file uploads via queries and mutations) to various GoLang GraphQL servers
Stars: ✭ 32 (-97.25%)
Mutual labels:  graphql, batch
Parabol
Free online agile retrospective meeting tool
Stars: ✭ 1,145 (-1.63%)
Mutual labels:  graphql
Graphql Microservices
Showcasing a graphql microservice setup
Stars: ✭ 68 (-94.16%)
Mutual labels:  graphql
Graphql Server
This is the core package for using GraphQL in a custom server easily
Stars: ✭ 65 (-94.42%)
Mutual labels:  graphql
App
Reusable framework for micro services & command line tools
Stars: ✭ 66 (-94.33%)
Mutual labels:  graphql
Vue Apollo Todos
Vue Apollo GraphQL mutation examples
Stars: ✭ 69 (-94.07%)
Mutual labels:  graphql
Hasura Actions Examples
Examples of handling custom business logic with Hasura Actions
Stars: ✭ 69 (-94.07%)
Mutual labels:  graphql
Socket.io Rpc
Extend your promises across a network with socket.io
Stars: ✭ 67 (-94.24%)
Mutual labels:  promise
Emittery
Simple and modern async event emitter
Stars: ✭ 1,146 (-1.55%)
Mutual labels:  promise
Script Reset Windows Update Tool
This script reset the Windows Update Components.
Stars: ✭ 68 (-94.16%)
Mutual labels:  batch
Apollo Cache Invalidation
Experimental cache invalidation tools for Apollo.
Stars: ✭ 66 (-94.33%)
Mutual labels:  graphql
Anime Downloader
A simple but powerful anime downloader and streamer.
Stars: ✭ 1,155 (-0.77%)
Mutual labels:  batch
Flowa
🔥Service level control flow for Node.js
Stars: ✭ 66 (-94.33%)
Mutual labels:  promise
Graphql Typescript
Define and build GraphQL Schemas using typed classes
Stars: ✭ 67 (-94.24%)
Mutual labels:  graphql
Apollo Server Vercel
⚫ Production-ready Node.js GraphQL server for Vercel Serverless Functions
Stars: ✭ 69 (-94.07%)
Mutual labels:  graphql

GraphQL::Batch

Build Status Gem Version

Provides an executor for the graphql gem which allows queries to be batched.

Installation

Add this line to your application's Gemfile:

gem 'graphql-batch'

And then execute:

$ bundle

Or install it yourself as:

$ gem install graphql-batch

Usage

Basic Usage

Schema Configuration

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.

class RecordLoader < GraphQL::Batch::Loader
  def initialize(model)
    @model = model
  end

  def perform(ids)
    @model.where(id: ids).each { |record| fulfill(record.id, record) }
    ids.each { |id| fulfill(id, nil) unless fulfilled?(id) }
  end
end

Use 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 (for graphql >= 1.5.0).

class MySchema < GraphQL::Schema
  query MyQueryType
  mutation MyMutationType

  use GraphQL::Batch
end

For pre 1.5.0 versions:

MySchema = GraphQL::Schema.define do
  query MyQueryType

  GraphQL::Batch.use(self)
end

Field Usage

The 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: true do
  argument :id, ID, required: true
end

def product(id:)
  RecordLoader.for(Product).load(id)
end

The 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: false do
  argument :ids, [ID], required: true
end

def products(ids:)
  RecordLoader.for(Product).load_many(ids)
end

Although 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.

Promises

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

def product_title(id:)
  RecordLoader.for(Product).load(id).then do |product|
    product.title
  end
end

You 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.

def product_image(id:)
  RecordLoader.for(Product).load(id).then do |product|
    RecordLoader.for(Image).load(product.image_id)
  end
end

If 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.

def all_collections
  Promise.all([
    CountLoader.for(Shop, :smart_collections).load(context.shop_id),
    CountLoader.for(Shop, :custom_collections).load(context.shop_id),
  ]).then do |results|
    results.reduce(&:+)
  end
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

def product(id:)
  # Try the cache first ...
  CacheLoader.for(Product).load(id).then(nil, lambda do |exc|
    # But if there's a connection error, go to the underlying database
    raise exc unless exc.is_a?(Redis::BaseConnectionError)
    logger.warn err.message
    RecordLoader.for(Product).load(id)
  end)
end

Unit Testing

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.

  def test_single_query
    product = products(:snowboard)
    title = GraphQL::Batch.batch do
      RecordLoader.for(Product).load(product.id).then(&:title)
    end
    assert_equal product.title, title
  end

Development

After 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.

Contributing

See our contributing guidelines for more information.

License

The gem is available as open source under the terms of the MIT License.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].