Class: ConsulSyncer::Wrapper

Inherits:
Object
  • Object
show all
Defined in:
lib/consul_syncer/wrapper.rb

Defined Under Namespace

Classes: ConsulError

Constant Summary collapse

BACKOFF =
[0.1, 0.5, 1.0, 2.0].freeze

Instance Method Summary collapse

Constructor Details

#initialize(consul_url, params:, logger:) ⇒ Wrapper

Returns a new instance of Wrapper.



14
15
16
17
18
19
# File 'lib/consul_syncer/wrapper.rb', line 14

def initialize(consul_url, params:, logger:)
  consul_url = "http://#{consul_url}" unless consul_url.include?("://")
  @consul = Faraday.new(consul_url)
  @params = params
  @logger = logger
end

Instance Method Details

#request(method, path, payload = nil) ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/consul_syncer/wrapper.rb', line 21

def request(method, path, payload = nil)
  if @params.any?
    separator = (path.include?("?") ? "&" : "?")
    path += "#{separator}#{URI.encode_www_form(@params)}"
  end
  args = [path]
  args << payload.to_json if payload

  retry_on_error do
    response = @consul.send(method, *args)
    if response.status == 200
      if method == :get
        JSON.parse(response.body)
      else
        true
      end
    else
      raise(
        ConsulError,
        "Failed to request #{response.env.method} #{response.env.url}: #{response.status} -- #{response.body}"
      )
    end
  end
end