Resource Caching

To improve the response time of GET requests, JR can cache the generated JSON fragments for Resources which are suitable. First, set config.resource_cache to an ActiveSupport cache store:

JSONAPI.configure do |config|
config.resource_cache = Rails.cache
end

Then, on each Resource you want to cache, call the caching method:

class PostResource < JSONAPI::Resource
caching
end

See the caveats section below for situations where you might not want to enable caching on particular Resources.

The Resource model must also have a field that is updated whenever any of the model’s data changes. The default Rails timestamps handle this pretty well, and the default cache key field is updated_at for this reason. You can use an alternate field (which you are then responsible for updating) by calling the cache_field method:

class Post < ActiveRecord::Base
before_save do
if self.change_counter.nil?
self.change_counter = 1
elsif self.changed?
self.change_counter += 1
end
end

after_touch do
update_attribute(:change_counter, self.change_counter + 1)
end
end

class PostResource < JSONAPI::Resource
caching
cache_field :change_counter
end

If context affects the content of the serialized result, you must define a class method attribute_caching_context on that Resource, which should return a different value for contexts that produce different results. In particular, if the meta or fetchable_fields methods, or any method providing the actual content of an attribute, changes depending on context, then you must provide attribute_caching_context. The actual value it returns isn’t important, what matters is that the value must be different if any relevant part of the context is different.

class PostResource < JSONAPI::Resource
caching

attributes :title, :body, :secret_field

def fetchable_fields
return super if context.user.superuser?
return super - [:secret_field]
end

def meta
if context.user.can_see_creation_dates?
return { created: _model.created_at }
else
return {}
end
end

def self.attribute_caching_context(context)
return {
admin: context.user.superuser?,
creation_date_viewer: context.user.can_see_creation_dates?
}
end
end

Caching Caveats

class MySerializer < JSONAPI::ResourceSerializer
def initialize(primary_resource_klass, options = {})
@my_special_option = options.delete(:my_special_option)
super
end

def config_description(resource_klass)
super.merge({my_special_option: @my_special_option})
end
end