Class: Millionsend::Request

Inherits:
Object
  • Object
show all
Defined in:
lib/millionsend/request.rb

Overview

Internal: builds and performs one HTTP call over net/http, then returns the parsed (symbol-keyed) body or raises a Millionsend::Error. The resource modules are thin wrappers over this.

Constant Summary collapse

VERBS =
{
  get: Net::HTTP::Get,
  post: Net::HTTP::Post,
  patch: Net::HTTP::Patch,
  delete: Net::HTTP::Delete,
}.freeze
TRANSPORT_ERRORS =

Transport-level failures that never produced an HTTP response -> the raised error carries status_code nil. Kept narrow so a mis-stubbed test (WebMock::NetConnectNotAllowedError) is not swallowed as a transport error.

[
  Timeout::Error, SocketError, SystemCallError, IOError,
  Net::OpenTimeout, Net::ReadTimeout, OpenSSL::SSL::SSLError
].freeze

Instance Method Summary collapse

Constructor Details

#initialize(method:, path:, body: nil, query: nil, idempotency_key: nil) ⇒ Request

Returns a new instance of Request.



29
30
31
32
33
34
35
# File 'lib/millionsend/request.rb', line 29

def initialize(method:, path:, body: nil, query: nil, idempotency_key: nil)
  @method = method
  @path = path
  @body = body
  @query = query
  @idempotency_key = idempotency_key
end

Instance Method Details

#performObject



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
# File 'lib/millionsend/request.rb', line 37

def perform
  api_key = Millionsend.api_key
  if api_key.nil? || api_key.to_s.empty?
    # Client-side failure: same class and stable name as a transport error,
    # so rescue Millionsend::ApplicationError / branching on e.name works.
    raise Millionsend::ApplicationError.new(
      "Missing API key. Set Millionsend.api_key or the MILLIONSEND_API_KEY environment variable.",
      nil, "application_error"
    )
  end

  uri = build_uri
  request = build_request(uri, api_key)

  response =
    begin
      Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http|
        http.request(request)
      end
    rescue *TRANSPORT_ERRORS => e
      raise Millionsend::ApplicationError.new(e.message, nil, "application_error")
    end

  handle(response)
end