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(options = {}) ⇒ Request

Returns a new instance of Request.



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

def initialize(options = {})
  @options = options
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
# 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|
    runtime = response.total_time&.round(3)

    @options[:monitor]&.call(
      {
        url: url, method: method, status: response.code, runtime: runtime,
        completed_at: Time.now.utc.iso8601(3), context: options[:monitoring_context]
      }
    )

    @options[:logger]&.info(
      {
        message: "Completed Chimera HTTP Request",
        method: method.upcase,
        url: url,
        code: response.code,
        runtime: runtime,
        user_agent: Typhoeus::Config.user_agent,
      }
    )

    @result = on_complete_handler(response)
  end

  @options[:logger]&.info(
    {
      message: "Starting Chimera HTTP Request",
      method: method.upcase,
      url: url,
      code: nil,
      runtime: 0,
      user_agent: Typhoeus::Config.user_agent,
    }
  )

  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