diff --git a/app/models/provider/synth.rb b/app/models/provider/synth.rb index b9523051..d1b6fe26 100644 --- a/app/models/provider/synth.rb +++ b/app/models/provider/synth.rb @@ -33,8 +33,7 @@ class Provider::Synth def fetch_exchange_rate(from:, to:, date:) retrying Provider::Base.known_transient_errors do |on_last_attempt| - response = Faraday.get("#{base_url}/rates/historical") do |req| - req.headers["Authorization"] = "Bearer #{api_key}" + response = client.get("#{base_url}/rates/historical") do |req| req.params["date"] = date.to_s req.params["from"] = from req.params["to"] = to @@ -69,6 +68,22 @@ class Provider::Synth "https://api.synthfinance.com" end + def app_name + "maybe_app" + end + + def app_type + Rails.application.config.app_mode + end + + def client + @client ||= Faraday.new(url: base_url) do |faraday| + faraday.headers["Authorization"] = "Bearer #{api_key}" + faraday.headers["X-Source"] = app_name + faraday.headers["X-Source-Type"] = app_type + end + end + def build_error(response) Provider::Base::ProviderError.new(<<~ERROR) Failed to fetch data from #{self.class} @@ -78,7 +93,7 @@ class Provider::Synth end def fetch_page(url, page, params = {}) - Faraday.get(url) do |req| + client.get(url) do |req| req.headers["Authorization"] = "Bearer #{api_key}" params.each { |k, v| req.params[k.to_s] = v.to_s } req.params["page"] = page diff --git a/test/models/provider/synth_test.rb b/test/models/provider/synth_test.rb index d487e426..575edf9f 100644 --- a/test/models/provider/synth_test.rb +++ b/test/models/provider/synth_test.rb @@ -17,18 +17,24 @@ class Provider::SynthTest < ActiveSupport::TestCase end test "retries then provides failed response" do - Faraday.expects(:get).returns(OpenStruct.new(success?: false)).times(3) + @client = mock + Faraday.stubs(:new).returns(@client) - response = @synth.fetch_exchange_rate from: "USD", to: "MXN", date: Date.current + @client.expects(:get).returns(OpenStruct.new(success?: false)).times(3) + + response = @synth.fetch_exchange_rate from: "USD", to: "MXN", date: Date.iso8601("2024-08-01") assert_match "Failed to fetch data from Provider::Synth", response.error.message end test "retrying, then raising on network error" do - Faraday.expects(:get).raises(Faraday::TimeoutError).times(3) + @client = mock + Faraday.stubs(:new).returns(@client) + + @client.expects(:get).raises(Faraday::TimeoutError).times(3) assert_raises Faraday::TimeoutError do - @synth.fetch_exchange_rate from: "USD", to: "MXN", date: Date.current + @synth.fetch_exchange_rate from: "USD", to: "MXN", date: Date.iso8601("2024-08-01") end end end