Class: EmailFuse::Request

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

Overview

This class is responsible for making the appropriate HTTP calls and raising the specific errors based on the response.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(path = "", body = {}, verb = "POST", options: {}) ⇒ Request

Returns a new instance of Request.



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/email_fuse/request.rb', line 9

def initialize(path = "", body = {}, verb = "POST", options: {})
  # Allow api_key override via options, fall back to global config
  api_key = options[:api_key] || EmailFuse.api_key
  raise if api_key.nil?

  api_key = api_key.call if api_key.is_a?(Proc)

  # Allow base_url override via options, fall back to global config
  @base_url = options[:base_url] || EmailFuse.base_url

  @path = path
  @body = body
  @verb = verb
  @options = options
  @headers = {
    "Content-Type" => "application/json",
    "Accept" => "application/json",
    "User-Agent" => "emailfuse-ruby:#{EmailFuse::VERSION}",
    "Authorization" => "Bearer #{api_key}"
  }

  set_idempotency_key
  set_batch_validation
end

Instance Attribute Details

#bodyObject

Returns the value of attribute body.



7
8
9
# File 'lib/email_fuse/request.rb', line 7

def body
  @body
end

#optionsObject

Returns the value of attribute options.



7
8
9
# File 'lib/email_fuse/request.rb', line 7

def options
  @options
end

#verbObject

Returns the value of attribute verb.



7
8
9
# File 'lib/email_fuse/request.rb', line 7

def verb
  @verb
end

Instance Method Details

#handle_error!(data, resp = nil) ⇒ Object

Raises:

  • (error_class)


46
47
48
49
50
51
52
53
54
# File 'lib/email_fuse/request.rb', line 46

def handle_error!(data, resp = nil)
  code = data[:statusCode]
  body = data[:message]
  headers = resp.respond_to?(:headers) ? resp.headers : (data[:headers] || {})

  # get error from the known list of errors
  error_class = EmailFuse::Error::ERRORS[code] || EmailFuse::Error
  raise error_class.new(body, code, headers)
end

#performObject

Performs the HTTP call



35
36
37
38
39
40
41
42
43
44
# File 'lib/email_fuse/request.rb', line 35

def perform
  options = build_request_options
  resp = HTTParty.send(@verb.to_sym, URI.join(@base_url, @path).to_s, options)

  check_json!(resp)
  data = process_response(resp)
  headers = extract_headers(resp)

  EmailFuse::Response.new(data, headers)
end