module WCC::Contentful::Middleware::Store
A Store
middleware wraps the Store
interface to perform any desired transformations on the Contentful
entries coming back from the store. A Store
middleware must implement the Store
interface as well as a `store=` attribute writer, which is used to inject the next store or middleware in the chain.
The Store
interface can be seen on the WCC::Contentful::Store::Base
class. It consists of the `#find, find_by
, find_all
, set, delete,` and `#index` methods.
Including this concern will define those methods to pass through to the next store. Any of those methods can be overridden on the implementing middleware. It will also expose two overridable methods, `#select?` and `#transform`. These methods are applied when reading values out of the store, and can be used to apply a filter or transformation to each entry in the store.
Attributes
Public Instance Methods
# File lib/wcc/contentful/middleware/store.rb, line 27 def call(store, *content_delivery_params, **_) instance = new(*content_delivery_params) instance.store = store instance end
# File lib/wcc/contentful/middleware/store.rb, line 34 def find(id, **options) found = store.find(id, **options) return transform(found) if found && (!has_select? || select?(found)) end
# File lib/wcc/contentful/middleware/store.rb, line 47 def find_all(options: nil, **args) DelegatingQuery.new( store.find_all(**args.merge(options: options)), middleware: self, options: options ) end
# File lib/wcc/contentful/middleware/store.rb, line 39 def find_by(options: nil, **args) result = store.find_by(**args.merge(options: options)) return unless result && (!has_select? || select?(result)) result = resolve_includes(result, options[:include]) if options && options[:include] transform(result) end
# File lib/wcc/contentful/middleware/store.rb, line 79 def has_select? # rubocop:disable Naming/PredicateName respond_to?(:select?) end
# File lib/wcc/contentful/middleware/store.rb, line 55 def resolve_includes(entry, depth) return entry unless entry && depth && depth > 0 WCC::Contentful::LinkVisitor.new(entry, :Link, depth: depth).map! do |val| resolve_link(val) end end
# File lib/wcc/contentful/middleware/store.rb, line 63 def resolve_link(val) return val unless resolved_link?(val) if !has_select? || select?(val) transform(val) else # Pretend it's an unresolved link - # matches the behavior of a store when the link cannot be retrieved WCC::Contentful::Link.new(val.dig('sys', 'id'), val.dig('sys', 'type')).to_h end end
# File lib/wcc/contentful/middleware/store.rb, line 75 def resolved_link?(value) value.is_a?(Hash) && value.dig('sys', 'type') == 'Entry' end
The default version of `#transform` just returns the entry. Override this with your own implementation.
# File lib/wcc/contentful/middleware/store.rb, line 85 def transform(entry) entry end