Sha256: 42e26c4b8f9e613ce5fbf612aca9298ba2488715035a8c2757a01c7e69b68080

Contents?: true

Size: 1.25 KB

Versions: 7

Compression:

Stored size: 1.25 KB

Contents

require 'reviewed/cache'

module Faraday
  class Cache

    def initialize(app)
      @app = app
    end

    def store
      Reviewed::Cache.store
    end

    def call(env)
      @url = env[:url]

      @website_id = env[:request_headers]['x-reviewed-website']

      if serve_from_cache? && store.exist?(cache_key)
        begin
          Hashie::Mash.new(MultiJson.load( store.read(cache_key) ))
        rescue => e
          raise e.message + ": #{cache_key}"
        end
      else
        @app.call(env).on_complete do |response|
          if store_response?(response)
            store.delete(cache_key)
            storeable_response = MultiJson.dump(response.slice(:status, :body, :response_headers))
            store.write(cache_key, storeable_response, write_options)
          end
        end
      end
    end

    private

    def serve_from_cache?
      @url.query.blank? || !@url.query.match(/\b(skip|reset)-cache\b/)
    end

    def store_response?(resp)
      return false if resp[:status] != 200
      @url.query.blank? || !@url.query.match(/\bskip-cache\b/)
    end

    def cache_key
      [@website_id, @url.request_uri].join(':')
    end

    def write_options
      { expires_in: Integer(ENV['REVIEWED_CACHE_TIMEOUT'] || 90).minutes }
    end

  end
end

Version data entries

7 entries across 7 versions & 1 rubygems

Version Path
reviewed-1.0.2 lib/faraday/cache.rb
reviewed-1.0.1 lib/faraday/cache.rb
reviewed-1.0.0 lib/faraday/cache.rb
reviewed-0.9.1 lib/faraday/cache.rb
reviewed-0.9.0 lib/faraday/cache.rb
reviewed-0.8.0 lib/faraday/cache.rb
reviewed-0.7.1 lib/faraday/cache.rb