Created
March 5, 2022 14:32
-
-
Save rmosolgo/b4e3cf0edd1ff6761a540ca2caceab6b to your computer and use it in GitHub Desktop.
ObjectCache with __typename
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require "bundler/inline" | |
gemfile do | |
gem "graphql", "1.13.10" | |
gem "graphql-pro", "1.21.4" | |
gem "graphql-enterprise", "1.1.3" | |
end | |
class CachingSchema < GraphQL::Schema | |
class BaseField < GraphQL::Schema::Field | |
include GraphQL::Enterprise::ObjectCache::FieldIntegration | |
cacheable(true) | |
end | |
class BaseObject < GraphQL::Schema::Object | |
field_class(BaseField) | |
include GraphQL::Enterprise::ObjectCache::ObjectIntegration | |
cacheable(true) | |
end | |
class Thing < BaseObject | |
field :name, String | |
end | |
class Query < BaseObject | |
field :thing, Thing, null: false | |
def thing | |
{ name: "something", id: "1" } | |
end | |
end | |
query(Query) | |
use GraphQL::Enterprise::ObjectCache, memory: true | |
def self.private_context_fingerprint_for(ctx) | |
ctx[:fingerprint] | |
end | |
def self.resolve_type(type, obj, ctx) | |
Thing | |
end | |
def self.id_from_object(obj, type, ctx) | |
obj[:id] | |
end | |
def self.object_fingerprint_for(object) | |
object.inspect | |
end | |
end | |
# Only typename: | |
res = CachingSchema.execute("{ __typename }") | |
pp res.to_h | |
# {"data"=>{"__typename"=>"Query"}} | |
pp res.context[:object_cache] | |
# {:public=>true, | |
# :hit=>false, | |
# :write=>true, | |
# :key=> | |
# "anonymous/f1bmfdIas_MNH_i3vtCIk_Cg24ZEmDYYmzYd0eVt20s=/0/RBNvo1WzZ4oRRq0W9-hknpT7T8If536DEMBg9hyq_4o=/", | |
# :messages=>["No cache entry was found"], | |
# :objects=>#<Set: {}>} | |
# Typename as part of a query: | |
res = CachingSchema.execute("{ thing { name __typename } }") | |
pp res.to_h | |
# {"data"=>{"thing"=>{"name"=>"something", "__typename"=>"Thing"}}} | |
pp res.context[:object_cache] | |
# {:public=>false, | |
# :hit=>false, | |
# :write=>true, | |
# :key=> | |
# "anonymous/P35Uwoli0lNrAwtsXYIK-S6ESu7X1oKc5PmGW_aJWL4=/0/RBNvo1WzZ4oRRq0W9-hknpT7T8If536DEMBg9hyq_4o=/", | |
# :messages=>["No cache entry was found"], | |
# :objects=>#<Set: {{:name=>"something", :id=>"1"}}>} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment