Class: SongstatsSDK::NetHTTPAdapter

Inherits:
Object
  • Object
show all
Defined in:
lib/songstats_sdk/http_client.rb

Constant Summary collapse

METHOD_MAP =
{
  get: Net::HTTP::Get,
  post: Net::HTTP::Post,
  delete: Net::HTTP::Delete
}.freeze

Instance Method Summary collapse

Instance Method Details

#request(method:, base_url:, path:, headers:, params:, json:, timeout:) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/songstats_sdk/http_client.rb', line 17

def request(method:, base_url:, path:, headers:, params:, json:, timeout:)
  uri = URI.join("#{base_url.chomp('/')}/", path.delete_prefix('/'))
  query = URI.encode_www_form(params || {})
  uri.query = [uri.query, query].compact.reject(&:empty?).join("&") unless query.empty?

  request_class = METHOD_MAP.fetch(method.to_sym) { raise ArgumentError, "Unsupported HTTP method: #{method}" }
  request = request_class.new(uri)
  headers.each { |key, value| request[key] = value unless value.nil? }

  if json
    request["content-type"] ||= "application/json"
    request.body = JSON.generate(json)
  end

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

  response = http.request(request)
  HTTPResponse.new(status: response.code.to_i, body: response.body.to_s, headers: response.to_hash)
end