Class: Svix::SvixHttpClient

Inherits:
Object
  • Object
show all
Defined in:
lib/svix/svix_http_client.rb

Instance Method Summary collapse

Constructor Details

#initialize(token, base_url) ⇒ SvixHttpClient

Returns a new instance of SvixHttpClient.



9
10
11
12
# File 'lib/svix/svix_http_client.rb', line 9

def initialize(token, base_url)
  @token = token
  @base_url = base_url
end

Instance Method Details

#execute_request(method, path, **kwargs) ⇒ Object



14
15
16
17
18
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
75
76
77
78
79
80
81
82
# File 'lib/svix/svix_http_client.rb', line 14

def execute_request(method, path, **kwargs)
  query_params = kwargs[:query_params] || {}
  headers = kwargs[:headers] || {}
  body = kwargs[:body] || {}

  uri = URI("#{@base_url}#{path}")
  encoded_query = encode_query_params(query_params)
  if encoded_query != ""
    uri.query = encoded_query
  end

  http = Net::HTTP.new(uri.host, uri.port)
  http.use_ssl = (uri.scheme == "https")

  # Dynamically select the request class based on method
  request_class = case method.to_s.upcase
  when "GET"
    Net::HTTP::Get
  when "POST"
    Net::HTTP::Post
  when "PUT"
    Net::HTTP::Put
  when "DELETE"
    Net::HTTP::Delete
  when "PATCH"
    Net::HTTP::Patch
  when "HEAD"
    Net::HTTP::Head
  else
    raise ArgumentError, "Unsupported HTTP method: #{method}"
  end

  # Create request object
  request = request_class.new(uri.request_uri)
  request["Authorization"] = "Bearer #{@token}"
  request["User-Agent"] = "svix-libs/#{VERSION}/ruby"
  request["svix-req-id"] = rand(0...(2 ** 64))

  # Add headers
  headers.each { |key, value| request[key] = value }

  # Check if idempotency-key header already exists
  if !request.key?("idempotency-key") && method.to_s.upcase == "POST"
    request["idempotency-key"] = "auto_" + SecureRandom.uuid_v4.to_s
  end

  # Add body for non-GET requests
  if %w[POST PUT PATCH].include?(method.to_s.upcase) && !body.nil?
    request.body = body.to_json
    request["Content-Type"] = "application/json"
  end

  res = execute_request_with_retries(request, http)

  # Execute request
  if Integer(res.code) == 204
    nil
  elsif Integer(res.code) >= 200 && Integer(res.code) <= 299
    JSON.parse(res.body)
  else
    fail(
      ApiError.new(
        :code => Integer(res.code),
        :response_headers => res.each_header.to_h,
        :response_body => res.body
      )
    )
  end
end