DeepBlueSeaArrow
DeepBlueSeaArrow

Reputation: 113

How to change the Auth header in every retry in Faraday client in ruby?

I have an HTTP get method defined in my Rails application something like this. I am wondering how can I update a new OAuth token in the headers on every single retry?

  def configure(service_base_uri, auth_header)
    Faraday.new(service_base_uri) do |faraday|
      faraday.headers['Authorization'] = auth_header
      faraday.request :retry, max: 5, interval: 0.05
      faraday.adapter Faraday.default_adapter
    end
  end

  def get(service_base_uri, path, error_message, params = {})
    auth_header = auth_token_generator(service_base_uri, path)

    connection = configure(service_base_uri, auth_header, headers)
    response = connection.get(parsed_uri.path, params)
    return JSON.parse(response.body)
  end

  def auth_token_generator(service_base_uri, path)
    # Some code
  end

Upvotes: 0

Views: 2153

Answers (1)

Casper
Casper

Reputation: 34308

The Faraday::Request::Retry class allows a parameter named retry_block.

retry_block - block that is executed after every retry. Request environment, middleware options, current number of retries and the exception is passed to the block as parameters.

Since the environment is passed into the block, you can use it to modify the headers for the next request:

 Faraday.new(...) do |faraday|
   faraday.headers['Authorization'] = auth_header
   faraday.request :retry, ...,
     retry_block: proc { |env, opts, retries, exception|
       env.request_headers['Authorization'] = "Hello #{retries}"
     }
 end

Upvotes: 2

Related Questions