Overview
Sources are a powerful feature that translate business objects with common structures into GraphQL elements. Think of sources as a portion of your schema that is deeply connected to another class in your Ruby application. If your classes follow a pattern, you can create a source for that pattern and translate all similar classes to GraphQL.Sources work through a hook-based system, allowing you to define how classes are translated into GraphQL objects, inputs, queries, mutations, and subscriptions.
Source Architecture
Sources extend fromRails::GraphQL::Source and use several key mechanisms:
Assignment Validation
Sources validate that they can handle specific classes:find_for! method locates the appropriate source for a given object:
Hook System
Sources use hooks to control the build process. Available hooks include:start- Runs before any other hookobject- Creates the GraphQL object typeinput- Creates the input typequery- Adds query fieldsmutation- Adds mutation fieldssubscription- Adds subscription fields
Managing Hooks
Adding Steps
Usestep to add hooks:
Controlling Hook Execution
Building Sources
Once defined, sources can be built selectively:Skipping Fields
Prevents specific fields from being created:Schema Attachment
Sources automatically attach to schemas based on namespaces:Fields are automatically added to schemas in the same namespace as the source.
Configuration
Add your source to the global configuration:Best Practices
Use safe_field
Prefer
safe_field over field in hooks to allow source classes to override fields:Mark Base as Abstract
Always mark your base source classes as abstract:
Selective Building
Only build what you need to avoid schema bloat:
Related Documentation
ActiveRecord Integration
Built-in source for ActiveRecord models
Events
Event system for hooks and callbacks