typhoeus: add a cache store for successful requests
This commit is contained in:
parent
f7c65e8b57
commit
a0ae1afb45
2 changed files with 61 additions and 0 deletions
21
app/lib/typhoeus/cache/successful_requests_rails_cache.rb
vendored
Normal file
21
app/lib/typhoeus/cache/successful_requests_rails_cache.rb
vendored
Normal file
|
@ -0,0 +1,21 @@
|
|||
module Typhoeus
|
||||
module Cache
|
||||
# Cache successful Typhoeus requests in the Rails cache
|
||||
# (but don’t cache failed requests).
|
||||
#
|
||||
# Usage:
|
||||
# Typhoeus.config.cache = Typhoeus::Cache::SuccessfulRequestsRailsCache.new
|
||||
# Typhoeus.get('http://exemple.com/api', cache_ttl: 1.day)
|
||||
class SuccessfulRequestsRailsCache
|
||||
def get(request)
|
||||
::Rails.cache.read(request)
|
||||
end
|
||||
|
||||
def set(request, response)
|
||||
if response&.success?
|
||||
::Rails.cache.write(request, response, expires_in: request.cache_ttl)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
40
spec/lib/typhoeus/cache/successful_requests_rails_cache.rb
vendored
Normal file
40
spec/lib/typhoeus/cache/successful_requests_rails_cache.rb
vendored
Normal file
|
@ -0,0 +1,40 @@
|
|||
require 'spec_helper'
|
||||
|
||||
describe Typhoeus::Cache::SuccessfulRequestsRailsCache, lib: true do
|
||||
let(:cache) { described_class.new }
|
||||
|
||||
let(:base_url) { "localhost:3001" }
|
||||
let(:request) { Typhoeus::Request.new(base_url, { :method => :get, cache: cache, cache_ttl: 1.day }) }
|
||||
let(:response) { Typhoeus::Response.new(:response_code => response_code, :return_code => 0, :mock => true) }
|
||||
let(:response_code) { 0 }
|
||||
|
||||
before { Rails.cache.clear }
|
||||
|
||||
describe "#set" do
|
||||
context 'when the request is successful' do
|
||||
let(:response_code) { 200 }
|
||||
|
||||
it 'saves the request in the Rails cache' do
|
||||
cache.set(request, response)
|
||||
expect(Rails.cache.exist?(request)).to be true
|
||||
expect(Rails.cache.read(request)).to be_a(Typhoeus::Response)
|
||||
end
|
||||
end
|
||||
|
||||
context 'when the request failed' do
|
||||
let(:response_code) { 500 }
|
||||
|
||||
it 'doesn’t save the request in the Rails cache' do
|
||||
cache.set(request, response)
|
||||
expect(Rails.cache.exist?(request)).to be false
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
describe "#get" do
|
||||
it 'returns the request in the cache' do
|
||||
Rails.cache.write(request, response)
|
||||
expect(cache.get(request)).to be_a(Typhoeus::Response)
|
||||
end
|
||||
end
|
||||
end
|
Loading…
Reference in a new issue