Class: Promoted::Ruby::Client::FaradayHTTPClient

Inherits:
Object
  • Object
show all
Defined in:
lib/promoted/ruby/client/faraday_http_client.rb

Instance Method Summary collapse

Constructor Details

#initialize(logger = nil) ⇒ FaradayHTTPClient

Returns a new instance of FaradayHTTPClient.



10
11
12
13
14
15
16
17
18
19
20
# File 'lib/promoted/ruby/client/faraday_http_client.rb', line 10

def initialize(logger = nil)
    @conn = Faraday.new do |f|
        f.request :json
        f.request :retry, max: 3
        if logger
          f.response :logger, logger, { headers: false, bodies: true, log_level: :debug }
        end
        f.use Faraday::Response::RaiseError # raises on 4xx and 5xx responses
        f.adapter :net_http_persistent
    end
end

Instance Method Details

#get(endpoint) ⇒ Object



38
39
40
# File 'lib/promoted/ruby/client/faraday_http_client.rb', line 38

def get(endpoint)
  @conn.get(endpoint).body
end

#send(endpoint, timeout_millis, request, additional_headers = {}) ⇒ Object



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/promoted/ruby/client/faraday_http_client.rb', line 22

def send(endpoint, timeout_millis, request, additional_headers={})
    response = @conn.post(endpoint) do |req|
        req.headers                 = req.headers.merge(additional_headers) if additional_headers
        req.headers['Content-Type'] = req.headers['Content-Type'] || 'application/json'
        req.options.timeout         = timeout_millis.to_f / 1000
        req.body                    = request.to_json
      end
        
      norm_headers = response.headers.transform_keys(&:downcase)
      if norm_headers["content-type"] != nil && norm_headers["content-type"].start_with?("application/json")
        Promoted::Ruby::Client::Util.translate_hash(JSON.parse(response.body))
      else
        response.body
      end
end