New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cache only cacheable status codes #90

Merged
merged 1 commit into from Jul 14, 2014
Jump to file or symbol
Failed to load files and symbols.
+29 −3
Diff settings

Always

Just for now

@@ -7,6 +7,15 @@ module FaradayMiddleware
# Public: Caches GET responses and pulls subsequent ones from the cache.
class Caching < Faraday::Middleware
attr_reader :cache
# Internal: List of status codes that can be cached:
# * 200 - 'OK'
# * 203 - 'Non-Authoritative Information'
# * 300 - 'Multiple Choices'
# * 301 - 'Moved Permanently'
# * 302 - 'Found'
# * 404 - 'Not Found'
# * 410 - 'Gone'
CACHEABLE_STATUS_CODES = [200, 203, 300, 301, 302, 404, 410]
extend Forwardable
def_delegators :'Faraday::Utils', :parse_query, :build_query
@@ -34,7 +43,14 @@ def call(env)
cache_on_complete(env)
else
# synchronous mode
response = cache.fetch(cache_key(env)) { @app.call(env) }
key = cache_key(env)
unless response = cache.read(key) and response
response = @app.call(env)
if CACHEABLE_STATUS_CODES.include?(response.status)
cache.write(key, response)
end
end
finalize_response(response, env)
end
else
@@ -63,7 +79,9 @@ def cache_on_complete(env)
finalize_response(cached_response, env)
else
response = @app.call(env)
response.on_complete { cache.write(key, response) }
if CACHEABLE_STATUS_CODES.include?(response.status)
response.on_complete { cache.write(key, response) }
end
end
end
View
@@ -13,7 +13,9 @@
response = lambda { |env|
[200, {'Content-Type' => 'text/plain'}, "request:#{request_count+=1}"]
}
broken = lambda { |env|
[500, {'Content-Type' => 'text/plain'}, "request:#{request_count+=1}"]
}
@conn = Faraday.new do |b|
b.use CachingLint
b.use FaradayMiddleware::Caching, @cache, options
@@ -22,6 +24,7 @@
stub.get('/?foo=bar', &response)
stub.post('/', &response)
stub.get('/other', &response)
stub.get('/broken', &broken)
end
end
end
@@ -58,6 +61,11 @@
expect(post('/').body).to eq('request:3')
end
it 'does not cache responses with invalid status code' do
expect(get('/broken').body).to eq('request:1')
expect(get('/broken').body).to eq('request:2')
end
context ":ignore_params" do
let(:options) { {:ignore_params => %w[ utm_source utm_term ]} }