Sha256: 50848282856cfbe76e752ad54504e9b71cf0587ce4f206121fd629d443fa43b8
Contents?: true
Size: 1.79 KB
Versions: 9
Compression:
Stored size: 1.79 KB
Contents
class LHC::Caching < LHC::Interceptor CACHE_VERSION = '1' # Options forwarded to the cache FORWARDED_OPTIONS = { cache_expires_in: :expires_in, cache_race_condition_ttl: :race_condition_ttl } def before_request(request) return unless request.options[:cache] cached_response_data = Rails.cache.fetch(key(request)) return unless cached_response_data Rails.logger.info "Served from cache: #{key(request)}" from_cache(request, cached_response_data) end def after_response(response) request = response.request return if !request.options[:cache] || !response.success? Rails.cache.write(key(request), to_cache(response), options(request.options)) end private # converts json we read from the cache to an LHC::Response object def from_cache(request, data) raw = Typhoeus::Response.new(data) request.response = LHC::Response.new(raw, request) end # converts a LHC::Response object to json, we store in the cache def to_cache(response) data = {} data[:body] = response.body data[:code] = response.code # convert into a actual hash because the typhoeus headers object breaks marshaling data[:headers] = response.headers ? Hash[response.headers] : response.headers # return_code is quite important as Typhoeus relies on it in order to determin 'success?' data[:return_code] = response.options[:return_code] data end def key(request) key = request.options[:cache_key] unless key key = "#{request.method.upcase} #{request.url}" key += "?#{request.params.to_query}" unless request.params.blank? end "LHC_CACHE(v#{CACHE_VERSION}): #{key}" end def options(input = {}) options = {} FORWARDED_OPTIONS.each do |k, v| options[v] = input[k] if input.key?(k) end options end end
Version data entries
9 entries across 9 versions & 1 rubygems