Rails GraphQL implements its own version of Rails GlobalID, uniquely identifying GraphQL components within your application. This feature is essential for request caching, compilation, and ActiveJob serialization.
Global IDs use a custom gql:// URI scheme specifically designed for GraphQL components.
# From lib/rails/graphql/global_id.rbclass << self # Create a new GraphQL Global identifier def create(object, options = nil) scope = options&.delete(:scope) || scope_of(object) new(URI::GQL.create(object, scope, options), options) end # Find the scope on which the object is applied to def scope_of(object) object.try(:schema_type) if object.gid_base_class.is_a?(Helpers::WithSchemaFields) endend
Global IDs integrate with ActiveJob for passing GraphQL objects to background jobs:
# From lib/rails/graphql/global_id.rbclass Serializer include Singleton # Determines if an argument should be serialized def serialize?(argument) argument.is_a?(Helpers::WithGlobalID) || argument.class.is_a?(Helpers::WithGlobalID) end # Serializes to JSON primitive def serialize(argument) { GlobalID::SERIALIZER_KEY => argument.to_global_id.to_s } end # Deserializes from JSON def deserialize(argument) GlobalID.find argument[GlobalID::SERIALIZER_KEY] endend
class ProcessFieldJob < ApplicationJob def perform(field) # field is automatically deserialized from GID puts field.gql_name endend# Automatically serializes to GIDfield = GraphQL::AppSchema[:query][:welcome]ProcessFieldJob.perform_later(field)
Global IDs provide stable references across processes:
# Store in cache or databasecached_field_gid = field.to_gid.to_s# Retrieve laterfield = GraphQL::GlobalID.find(cached_field_gid)
Background Jobs
Pass GraphQL components to jobs safely:
ProcessSchemaJob.perform_later(GraphQL::AppSchema)# Automatically serializes/deserializes via GID
Version Awareness
Remember that Global IDs don’t include version information:
# If schema changes, cached GIDs may become invalid# Use Type Map version for cache invalidationcache_key = [field.to_gid.to_s, GraphQL.type_map.version].join('/')