typhoeus: add a cache store for successful requests

This commit is contained in:
Pierre de La Morinerie 2018-12-06 13:21:05 +00:00
parent f7c65e8b57
commit a0ae1afb45
2 changed files with 61 additions and 0 deletions

View file

@ -0,0 +1,21 @@
module Typhoeus
module Cache
# Cache successful Typhoeus requests in the Rails cache
# (but dont 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

View 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 'doesnt 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