From 98646ed98d5a85053da709c4a46442d01df14bbd Mon Sep 17 00:00:00 2001 From: Joe Gaudet Date: Fri, 21 Apr 2017 11:35:52 -0700 Subject: [PATCH] Fix an issue with redis keys not hitting When writing to a redis store, the keys used by JR are converted to slash delimited strings. So: key = [record_type, id, updated at] Gets converted to record_type/id/updated_at This causes the lookup function to never get hits from the redis store. This commit adds a configurable function to allow formating of the lookup key. --- lib/jsonapi/cached_resource_fragment.rb | 5 +++++ lib/jsonapi/configuration.rb | 10 ++++++++++ 2 files changed, 15 insertions(+) diff --git a/lib/jsonapi/cached_resource_fragment.rb b/lib/jsonapi/cached_resource_fragment.rb index 4a6d598d4..eb76535ef 100644 --- a/lib/jsonapi/cached_resource_fragment.rb +++ b/lib/jsonapi/cached_resource_fragment.rb @@ -81,6 +81,11 @@ def self.lookup(resource_klass, serializer_config_key, context, context_key, cac hits = JSONAPI.configuration.resource_cache.read_multi(*keys).reject{|_,v| v.nil? } return keys.each_with_object({}) do |key, hash| (_, id, _, _) = key + + if JSONAPI.configuration.resource_cache_key_format_function + key = JSONAPI.configuration.resource_cache_key_format_function(key) + end + if hits.has_key?(key) hash[id] = self.from_cache_value(resource_klass, context, hits[key]) else diff --git a/lib/jsonapi/configuration.rb b/lib/jsonapi/configuration.rb index 52c34ab81..fe2fbef21 100644 --- a/lib/jsonapi/configuration.rb +++ b/lib/jsonapi/configuration.rb @@ -35,6 +35,7 @@ class Configuration :resource_cache, :default_resource_cache_field, :resource_cache_digest_function, + :resource_cache_key_format_function, :resource_cache_usage_report_function def initialize @@ -140,6 +141,12 @@ def initialize # Optionally provide a callable which JSONAPI will call with information about cache # performance. Should accept three arguments: resource name, hits count, misses count. self.resource_cache_usage_report_function = nil + + # Resource cache key formating + # Optionally provide a callable which JSONAPI will call in order to format your cache + # key, this is useful for stores such as redis, which cannot be queried using an array + # the way the rails in memory cache can + self.resource_cache_usage_report_function = nil end def cache_formatters=(bool) @@ -256,7 +263,10 @@ def default_record_accessor_klass=(default_record_accessor_klass) attr_writer :resource_cache_digest_function + attr_writer :resource_cache_key_format_function + attr_writer :resource_cache_usage_report_function + end class << self