Class: Resent::Client

Inherits:
Object
  • Object
show all
Defined in:
lib/resent/client.rb

Overview

Official Resent API client.

resent = Resent::Client.new(ENV.fetch("RESENT_API_KEY"))
result = resent.emails.send(
from: "Acme <noreply@yourdomain.com>",
to: "you@example.com",
subject: "Hello",
html: "<strong>It works!</strong>"
)

Constant Summary collapse

DEFAULT_BASE_URL =
"https://resent.one/api/v1"

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(api_key = nil, base_url: DEFAULT_BASE_URL) ⇒ Client

Returns a new instance of Client.

Raises:



32
33
34
35
36
37
38
# File 'lib/resent/client.rb', line 32

def initialize(api_key = nil, base_url: DEFAULT_BASE_URL)
  key = (api_key || ENV["RESENT_API_KEY"]).to_s.strip
  raise Error, "Missing API key. Pass Resent::Client.new(key) or set RESENT_API_KEY." if key.empty?

  @api_key = key
  @base_url = base_url.to_s.sub(%r{/+\z}, "")
end

Instance Attribute Details

#api_keyObject (readonly)

Returns the value of attribute api_key.



30
31
32
# File 'lib/resent/client.rb', line 30

def api_key
  @api_key
end

#base_urlObject (readonly)

Returns the value of attribute base_url.



30
31
32
# File 'lib/resent/client.rb', line 30

def base_url
  @base_url
end

Instance Method Details

#emailsObject



40
41
42
# File 'lib/resent/client.rb', line 40

def emails
  Emails.new(self)
end

#request(method, path, body: nil) ⇒ Object



44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
# File 'lib/resent/client.rb', line 44

def request(method, path, body: nil)
  uri = URI("#{@base_url}/#{path.sub(%r{\A/}, "")}")
  http = Net::HTTP.new(uri.host, uri.port)
  http.use_ssl = uri.scheme == "https"
  http.open_timeout = 15
  http.read_timeout = 30

  request = case method.to_s.upcase
            when "POST" then Net::HTTP::Post.new(uri)
            when "GET" then Net::HTTP::Get.new(uri)
            else
              raise Error, "Unsupported HTTP method: #{method}"
            end

  request["Authorization"] = "Bearer #{api_key}"
  request["Accept"] = "application/json"
  request["Content-Type"] = "application/json"
  request["User-Agent"] = "resent-ruby/#{VERSION}"
  request.body = JSON.generate(body) if body

  response = http.request(request)
  parsed = parse_json(response.body)

  unless response.is_a?(Net::HTTPSuccess)
    message = if parsed.is_a?(Hash) && parsed["error"]
                parsed["error"].to_s
              else
                "Resent API error (#{response.code})"
              end
    raise Error.new(message, status: response.code.to_i, body: parsed)
  end

  parsed
end