Overview
Sources in Rails GraphQL provide a powerful abstraction for bridging data models to your GraphQL schema. They automatically generate objects, inputs, queries, and mutations based on your underlying data structure.What is a Source?
A source is an abstract object that contains fields, objects, and operations which are delivered to your schemas through proxies. Sources maintain ownership of objects while making them available across multiple schemas and namespaces.Built-in Sources
Rails GraphQL includesActiveRecordSource for bridging ActiveRecord models:
Creating a Custom Source
Basic Structure
Inherit fromRails::GraphQL::Source::Base:
Assignment
Connect your source to a Ruby class:Source Hooks
Sources use hooks to define schema elements at different stages:Available Hooks
:start- Initial setup:object- Build object type fields:input- Build input type fields:query- Build query fields:mutation- Build mutation fields:subscription- Build subscription fields
Defining Hooks
Accessing Source Components
Object Type
Access or create the GraphQL object type:Input Type
Access or create the GraphQL input type:Real-World Example: REST API Source
Create a source that bridges a REST API:Example: MongoDB Source
Create a source for MongoDB documents:Field Management
safe_field
Use safe_field to add fields that respect skip rules:
Skipping Fields
Skip fields globally:Only Fields
Limit fields for specific types:Namespaces
Sources can belong to multiple namespaces:Attaching to Schemas
Sources automatically attach to schemas in their namespaces:Advanced Features
Custom Type Creation
Create additional types:Validation
Validate assignments:Hooks with Context
Access source context in hooks:Best Practices
Use Abstract Base Classes
Use Abstract Base Classes
Create abstract source classes for common patterns:
Skip Sensitive Fields
Skip Sensitive Fields
Always skip fields containing sensitive data:
Use safe_field
Use safe_field
Always use
safe_field instead of field to respect skip rules.Validate in Resolvers
Validate in Resolvers
Implement proper validation and error handling in resolver methods.
Document Your Source
Document Your Source
Add comments explaining what data model your source bridges and any special behavior.
Testing Sources
Next Steps
ActiveRecord Source
Learn about the built-in ActiveRecord source
Namespaces
Organize your schemas with namespaces