Class: Trigv::Client

Inherits:
Object
  • Object
show all
Defined in:
lib/trigv/client.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(api_key: nil, base_url: Validation::DEFAULT_BASE_URL, timeout: Validation::DEFAULT_TIMEOUT, max_retries: Validation::MAX_RETRIES) ⇒ Client

Returns a new instance of Client.

Raises:



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/trigv/client.rb', line 24

def initialize(
  api_key: nil,
  base_url: Validation::DEFAULT_BASE_URL,
  timeout: Validation::DEFAULT_TIMEOUT,
  max_retries: Validation::MAX_RETRIES
)
  api_key ||= ENV.fetch('TRIGV_API_KEY', nil)
  api_key = api_key&.strip
  raise ValidationError, 'api_key is required (or set TRIGV_API_KEY)' if api_key.nil? || api_key.empty?
  raise ValidationError, 'max_retries must be zero or greater' if max_retries.negative?
  raise ValidationError, 'timeout must be greater than zero' if timeout <= 0

  @api_key = api_key
  @base_url = base_url.to_s.chomp('/')
  @timeout = timeout
  @max_retries = max_retries
end

Instance Attribute Details

#api_keyObject (readonly)

Returns the value of attribute api_key.



22
23
24
# File 'lib/trigv/client.rb', line 22

def api_key
  @api_key
end

#base_urlObject (readonly)

Returns the value of attribute base_url.



22
23
24
# File 'lib/trigv/client.rb', line 22

def base_url
  @base_url
end

#max_retriesObject (readonly)

Returns the value of attribute max_retries.



22
23
24
# File 'lib/trigv/client.rb', line 22

def max_retries
  @max_retries
end

#timeoutObject (readonly)

Returns the value of attribute timeout.



22
23
24
# File 'lib/trigv/client.rb', line 22

def timeout
  @timeout
end

Instance Method Details

#send_event(**params) ⇒ Object



46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/trigv/client.rb', line 46

def send_event(**params)
  body = Validation.validate_send_event_params(params)
  has_idempotency = body.key?('idempotency_key')

  request_with_retry(:post, '/v1/events', body, allow_retry: has_idempotency) do |status, parsed, headers|
    if [200, 202].include?(status) && parsed&.dig('event')
      event = parse_event(parsed['event'])
      SendEventResult.new(event: event, duplicate: status == 200)
    else
      error_from_response(status, parsed, headers)
    end
  end
end

#user_agentObject



42
43
44
# File 'lib/trigv/client.rb', line 42

def user_agent
  "trigv-ruby/#{VERSION}"
end

#verify_connectionObject



60
61
62
63
64
65
66
67
68
# File 'lib/trigv/client.rb', line 60

def verify_connection
  request_with_retry(:get, '/v1/connection', nil, allow_retry: true) do |status, parsed, headers|
    if status == 200 && parsed&.dig('workspace') && parsed['api_key']
      parse_connection_result(parsed)
    else
      error_from_response(status, parsed, headers)
    end
  end
end