Class: Resend::Request

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

Overview

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

Constant Summary collapse

BASE_URL =
ENV["RESEND_BASE_URL"] || "https://api.resend.com/"

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

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

Returns a new instance of Request.



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/resend/request.rb', line 11

def initialize(path = "", body = {}, verb = "POST", options: {})
  raise if (api_key = Resend.api_key).nil?

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

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

  set_idempotency_key
end

Instance Attribute Details

#bodyObject

Returns the value of attribute body.



9
10
11
# File 'lib/resend/request.rb', line 9

def body
  @body
end

#optionsObject

Returns the value of attribute options.



9
10
11
# File 'lib/resend/request.rb', line 9

def options
  @options
end

#verbObject

Returns the value of attribute verb.



9
10
11
# File 'lib/resend/request.rb', line 9

def verb
  @verb
end

Instance Method Details

#handle_error!(resp) ⇒ Object

Raises:

  • (error)


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

def handle_error!(resp)
  code = resp[:statusCode]
  body = resp[:message]

  # get error from the known list of errors
  error = Resend::Error::ERRORS[code]
  raise(error.new(body, code)) if error

  # Raise generic Resend error when the error code is not part of the known errors
  raise Resend::Error.new(body, code)
end

#performObject

Performs the HTTP call



31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/resend/request.rb', line 31

def perform
  options = {
    headers: @headers
  }
  options[:body] = @body.to_json unless @body.empty?

  resp = HTTParty.send(@verb.to_sym, "#{BASE_URL}#{@path}", options)

  check_json!(resp)

  resp.transform_keys!(&:to_sym) unless resp.body.empty?
  handle_error!(resp) if resp[:statusCode] && (resp[:statusCode] != 200 || resp[:statusCode] != 201)
  resp
end