Dataloader
GraphQL::Dataloader instances are created for each query (or multiplex) and they:
-
Cache Source instances for the duration of
GraphQLexecution -
Run pending Fibers to resolve data requirements and continue
GraphQLexecution
During a query, you can access the dataloader instance with:
-
GraphQL::Query::Context#dataloader(context.dataloader, anywhere that query context is available) -
GraphQL::Schema::Object#dataloader(dataloaderinside a resolver method) -
GraphQL::Schema::Resolver#dataloader(dataloaderinsidedef resolveof a Resolver, Mutation, or Subscription class.)
Fiber Lifecycle Hooks
Under the hood, Dataloader creates Fibers as-needed and uses them to run GraphQL and load data from Source classes. You can hook into these Fibers through several lifecycle hooks. To implement these hooks, create a custom subclass and provide new implementation for these methods:
class MyDataloader < GraphQL::Dataloader # or GraphQL::Dataloader::AsyncDataloader # ... end
Then, use your customized dataloader instead of the built-in one:
class MySchema < GraphQL::Schema - use GraphQL::Dataloader + use MyDataloader end
-
GraphQL::Dataloader#get_fiber_variablesis called before creating a Fiber. By default, it returns a hash containing the parent Fiber’s variables (fromThread.current[...]). You can add to this hash in your own implementation of this method. -
GraphQL::Dataloader#set_fiber_variablesis called inside the new Fiber. It’s passed the hash returned fromget_fiber_variables. You can use this method to initialize “global” state inside the new Fiber. -
GraphQL::Dataloader#cleanup_fiberis called just before a Dataloader Fiber exits. You can use this methods to teardown any state that you prepared inset_fiber_variables.