Class: EsHttpClient::Connection

Inherits:
Object
  • Object
show all
Defined in:
lib/es_http_client/connection.rb

Instance Method Summary collapse

Constructor Details

#initialize(endpoint, username = nil, password = nil) ⇒ Connection

Returns a new instance of Connection.



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/es_http_client/connection.rb', line 11

def initialize(endpoint, username=nil, password=nil)
  STDERR.puts "Faraday connecting to #{endpoint}"
  @connection = Faraday.new(url: endpoint) do |faraday|
    faraday.request :retry, max: 4, interval: 0.05, interval_randomness: 0.5, backoff_factor: 2
    faraday.response :json, content_type: 'application/json'
    faraday.response :mashify
    faraday.adapter Faraday.default_adapter
    faraday.use ErrorHandler
  end
  @headers = {
    'Accept'       => 'application/json',
    'Content-Type' => 'application/json'
  }
  if username && password
    token = Base64.encode64("#{username}:#{password}")[0..-2]
    @headers.merge!({ 'Authorization' => "Basic #{token}" })
  end
end

Instance Method Details

#get(uri, etag) ⇒ Object



30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/es_http_client/connection.rb', line 30

def get(uri, etag)
  response = @connection.send(:get, uri) do |req|
    req.headers = @headers
    req.headers.merge({ 'If-None-Match' => etag, 'ES-LongPoll' => 10 }) if etag
    req.body = {}.to_json
    req.params['embed'] = 'body'
  end
  response
rescue EsHttpClientError => e
  STDERR.puts "Faraday: Error response #{e}"
  raise e
end

#post(uri, event, expected_version) ⇒ Object



43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/es_http_client/connection.rb', line 43

def post(uri, event, expected_version)
  @connection.send(:post, uri) do |req|
    req.headers = {
      'Accept'        => 'application/json',
      'Content-Type'  => 'application/json',
      'ES-EventType' => event.type,
      'ES-EventId'   => event.id,
      'ES-ExpectedVersion' => expected_version.to_s
    }
    req.body = event.data.to_json
  end
end