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") ⇒ Request

Returns a new instance of Request.



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

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

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

Instance Attribute Details

#bodyObject

Returns the value of attribute body.



13
14
15
# File 'lib/resend/request.rb', line 13

def body
  @body
end

#verbObject

Returns the value of attribute verb.



13
14
15
# File 'lib/resend/request.rb', line 13

def verb
  @verb
end

Instance Method Details

#handle_error!(resp) ⇒ Object

Raises:

  • (error)


42
43
44
45
46
47
# File 'lib/resend/request.rb', line 42

def handle_error!(resp)
  code = resp[:statusCode]
  body = resp[:message]
  error = Resend::Error::ERRORS[code]
  raise(error.new(body, code)) if error
end

#performObject

Performs the HTTP call



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

def perform
  options = {
    headers: @headers
  }

  options[:body] = @body.to_json unless @body.empty?
  resp = HTTParty.send(@verb.to_sym, "#{BASE_URL}#{@path}", options)
  resp.transform_keys!(&:to_sym) unless resp.body.empty?
  handle_error!(resp) if resp[:statusCode] && (resp[:statusCode] != 200 || resp[:statusCode] != 201)
  resp
end