Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 20 additions & 2 deletions lib/faraday_middleware/response/caching.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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

Expand Down
10 changes: 9 additions & 1 deletion spec/caching_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -22,6 +24,7 @@
stub.get('/?foo=bar', &response)
stub.post('/', &response)
stub.get('/other', &response)
stub.get('/broken', &broken)
end
end
end
Expand Down Expand Up @@ -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 ]} }

Expand Down