lib/wcc/contentful/middleware/store/caching_middleware.rb in wcc-contentful-1.3.2 vs lib/wcc/contentful/middleware/store/caching_middleware.rb in wcc-contentful-1.4.0.rc1
- old
+ new
@@ -4,12 +4,16 @@
class CachingMiddleware
include WCC::Contentful::Middleware::Store
# include instrumentation, but not specifically store stack instrumentation
include WCC::Contentful::Instrumentation
- attr_accessor :expires_in
+ attr_accessor :expires_in, :configuration
+ def default_locale
+ @default_locale ||= configuration&.default_locale&.to_s || 'en-US'
+ end
+
def initialize(cache = nil)
@cache = cache || ActiveSupport::Cache::MemoryStore.new
@expires_in = nil
end
@@ -20,25 +24,38 @@
event = 'miss'
# if it's not a contentful ID don't hit the API.
# Store a nil object if we can't find the object on the CDN.
(store.find(key, **options) || nil_obj(key)) if key =~ /^\w+$/
end
- _instrument(event, key: key, options: options)
- case found.try(:dig, 'sys', 'type')
- when 'Nil', 'DeletedEntry', 'DeletedAsset'
- nil
- else
- found
+ return unless found
+ return if %w[Nil DeletedEntry DeletedAsset].include?(found.dig('sys', 'type'))
+
+ # If what we found in the cache is for the wrong Locale, go hit the store directly.
+ # Now that the one locale is in the cache, when we index next time we'll index the
+ # all-locales version and we'll be fine.
+ locale = options[:locale]&.to_s || default_locale
+ if found.dig('sys', 'locale') != locale
+ event = 'miss'
+ return store.find(key, **options)
end
+
+ found
+ ensure
+ _instrument(event, key: key, options: options)
end
# TODO: https://github.com/watermarkchurch/wcc-contentful/issues/18
# figure out how to cache the results of a find_by query, ex:
# `find_by('slug' => '/about')`
def find_by(content_type:, filter: nil, options: nil)
+ options ||= {}
if filter&.keys == ['sys.id'] && found = @cache.read(filter['sys.id'])
- return found
+ # This is equivalent to a find, usually this is done by the resolver to
+ # try to include deeper relationships. Since we already have this object,
+ # don't hit the API again.
+ return if %w[Nil DeletedEntry DeletedAsset].include?(found.dig('sys', 'type'))
+ return found if found.dig('sys', 'locale') == options[:locale]
end
store.find_by(content_type: content_type, filter: filter, options: options)
end