Class: ChimeraHttpClient::Request

Inherits:
Object
  • Object
show all
Defined in:
lib/chimera_http_client/request.rb

Constant Summary collapse

TIMEOUT_SECONDS =
3

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(logger: nil) ⇒ Request



7
8
9
# File 'lib/chimera_http_client/request.rb', line 7

def initialize(logger: nil)
  @logger = logger
end

Instance Attribute Details

#requestObject (readonly)

Returns the value of attribute request.



5
6
7
# File 'lib/chimera_http_client/request.rb', line 5

def request
  @request
end

#resultObject (readonly)

Returns the value of attribute result.



5
6
7
# File 'lib/chimera_http_client/request.rb', line 5

def result
  @result
end

Instance Method Details

#create(url:, method:, body: nil, options: {}, headers: {}) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/chimera_http_client/request.rb', line 19

def create(url:, method:, body: nil, options: {}, headers: {})
  request_params = {
    method:          method,
    body:            body,
    params:          options[:params] || {},
    headers:         headers,
    timeout:         options[:timeout] || TIMEOUT_SECONDS,
    accept_encoding: "gzip",
    cache:           options[:cache],
  }

  # Basic-auth support:
  username = options.fetch(:username, nil)
  password = options.fetch(:password, nil)
  request_params[:userpwd] = "#{username}:#{password}" if username && password

  @request = Typhoeus::Request.new(url, request_params)

  @result = nil
  @request.on_complete do |response|
    @logger&.info("Completed HTTP request: #{method.upcase} #{url} " \
      "in #{response.total_time&.round(3)}sec with status code #{response.code}")

    @result = on_complete_handler(response)
  end

  @logger&.info("Starting HTTP request: #{method.upcase} #{url}")

  self
end

#run(url:, method:, body: nil, options: {}, headers: {}) ⇒ Object



11
12
13
14
15
16
17
# File 'lib/chimera_http_client/request.rb', line 11

def run(url:, method:, body: nil, options: {}, headers: {})
  create(url: url, method: method, body: body, options: options, headers: headers)

  @request.run

  @result
end