Sha256: 6b5a33b329e1535b89559e35f9f144c6fb7985d2ca360c6b8e3d5930c976860e

Contents?: true

Size: 1.26 KB

Versions: 8

Compression:

Stored size: 1.26 KB

Contents

require "faraday/middleware"

module ZendeskAPI
  module Middleware
    module Request
      # Request middleware that caches responses based on etags
      # can be removed once this is merged: https://github.com/pengwynn/faraday_middleware/pull/42
      # @private
      class EtagCache < Faraday::Middleware
        def initialize(app, options = {})
          @app = app
          @cache = options[:cache] ||
            raise("need :cache option e.g. ActiveSupport::Cache::MemoryStore.new")
          @cache_key_prefix = options.fetch(:cache_key_prefix, :faraday_etags)
        end

        def call(env)
          return @app.call(env) unless [:get, :head].include?(env[:method])
          cache_key = [@cache_key_prefix, env[:url].to_s]

          # send known etag
          if cached = @cache.read(cache_key)
            env[:request_headers]["If-None-Match"] ||= cached[:response_headers]["Etag"]
          end

          @app.call(env).on_complete do
            if cached && env[:status] == 304 # not modified
              env[:body] = cached[:body]
            end

            if env[:status] == 200 && env[:response_headers]["Etag"] # modified and cacheable
              @cache.write(cache_key, env)
            end
          end
        end
      end
    end
  end
end

Version data entries

8 entries across 8 versions & 1 rubygems

Version Path
zendesk_api-0.2.5 lib/zendesk_api/middleware/request/etag_cache.rb
zendesk_api-0.2.4 lib/zendesk_api/middleware/request/etag_cache.rb
zendesk_api-0.2.2 lib/zendesk_api/middleware/request/etag_cache.rb
zendesk_api-0.2.1 lib/zendesk_api/middleware/request/etag_cache.rb
zendesk_api-0.1.11 lib/zendesk_api/middleware/request/etag_cache.rb
zendesk_api-0.1.10 lib/zendesk_api/middleware/request/etag_cache.rb
zendesk_api-0.1.9 lib/zendesk_api/middleware/request/etag_cache.rb
zendesk_api-0.1.8 lib/zendesk_api/middleware/request/etag_cache.rb