Class: SuperSendTX::HttpClient

Inherits:
Object
  • Object
show all
Defined in:
lib/supersendtx/http.rb

Constant Summary collapse

DEFAULT_API_BASE_URL =
"https://api.supersendtx.com"

Instance Method Summary collapse

Constructor Details

#initialize(api_key, base_url: DEFAULT_API_BASE_URL, transport: nil) ⇒ HttpClient

Returns a new instance of HttpClient.

Raises:

  • (ArgumentError)


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

def initialize(api_key, base_url: DEFAULT_API_BASE_URL, transport: nil)
  raise ArgumentError, "SuperSend TX API key must start with stx_" unless api_key.start_with?("stx_")

  @api_key = api_key
  @base_url = base_url.chomp("/")
  @transport = transport
end

Instance Method Details

#query(params) ⇒ Object



44
45
46
47
48
49
# File 'lib/supersendtx/http.rb', line 44

def query(params)
  filtered = params.compact
  return "" if filtered.empty?

  "?#{URI.encode_www_form(filtered)}"
end

#request(method, path, body: nil, 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
# File 'lib/supersendtx/http.rb', line 19

def request(method, path, body: nil, headers: {})
  request_headers = {
    "Authorization" => "Bearer #{@api_key}",
    "Content-Type" => "application/json"
  }.merge(headers)

  return @transport.call(method, path, body, request_headers) if @transport

  uri = URI.parse("#{@base_url}#{path}")
  http = Net::HTTP.new(uri.host, uri.port)
  http.use_ssl = uri.scheme == "https"

  request_class = Net::HTTP.const_get(method.capitalize)
  request = request_class.new(uri.request_uri)
  request_headers.each { |key, value| request[key] = value }
  request.body = JSON.generate(body) if body

  response = http.request(request)
  parsed = response.body.to_s.empty? ? {} : JSON.parse(response.body)

  raise Error.from_response(response.code.to_i, parsed) if response.code.to_i >= 400

  parsed
end