Repository navigation
GraphQL::ResultCache (v0.1.x)
Fu Ying edited this page Nov 18, 2021
·
3 revisions
This gem is to cache the json result, instead of resolved object.
Add this line to your application's Gemfile:
gem 'graphql-result_cache', '~> 0.1.8'And then execute:
$ bundle
Or install it yourself as:
$ gem install graphql-result_cache
- Use
GraphQL::ResultCacheas a plugin in your schema.
class MySchema < GraphQL::Schema
mutation Types::MutationType
query Types::QueryType
use GraphQL::ResultCache
end- Add the custom field class to accept
result_cachemetadata.
module Types
class BaseObject < GraphQL::Schema::Object
field_class GraphQL::ResultCache::Field
end
end- Config the fields which need to be cached with
result_cachedefinition.
field :theme, Types::ThemeType, null: false, result_cache: true- Wrap query result with
GraphQL::ResultCache::Result.
class GraphqlController < ApplicationController
def execute
# ...
result = if params[:_json]
multiple_execute(params[:_json], context: context)
else
execute_query(context: context)
end
render json: GraphQL::ResultCache::Result.new(result)
end
endfield :theme, Types::ThemeType, null: false, result_cache: { if: :published? }The if condition can be either a Symbol or a Proc.
By default, GraphQL::ResultCache will generate a cache key combining the field path, arguments and object.
But you can customize the object clause by specify the key option.
field :theme, Types::ThemeType, null: false, result_cache: { key: :theme_cache_key }The key can be either a Symbol or a Proc.
An after_process callback can be provided, eg. when some dynamic values need to be amended after cached result applied.
field :theme, Types::ThemeType, null: false, result_cache: { after_process: :amend_dynamic_attributes }
def amend_dynamic_attributes(theme_node)
theme_node.merge! used_count: object.theme.used_count
endGraphQL::ResultCache can be configured in initializer.
# config/initializers/graphql/result_cache.rb
GraphQL::ResultCache.configure do |config|
config.namespace = "GraphQL:Result" # Cache key namespace
config.expires_in = 1.hour # Expire time for the cache, default to 1.hour
config.client_hash = -> { Rails.cache.read(:deploy_version) } # GraphQL client package hash key, used in cache key generation, default to nil
config.except = ->(ctx) { !ctx[:result_cacheable] } # Exception rule, skip the cache while evaluated as true, default to nil
config.cache = Rails.cache # The cache object, default to Rails.cache in Rails
config.logger = Rails.logger # The Logger, default to Rails.logger in Rails
endWhen using with introspection, you need to assign custom introspection to avoid getting the nullable type for a non-null type.
class MySchema < GraphQL::Schema
introspection ::GraphQL::ResultCache::Introspection
end