Class: Emailable::Client

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

Constant Summary collapse

ERRORS =
{
  400 => BadRequestError,
  401 => UnauthorizedError,
  402 => PaymentRequiredError,
  403 => ForbiddenError,
  404 => NotFoundError,
  429 => TooManyRequestsError,
  500 => InternalServerError,
  503 => ServiceUnavailableError
}.freeze

Instance Method Summary collapse

Constructor Details

#initializeClient

Returns a new instance of Client.



14
15
16
17
# File 'lib/emailable/client.rb', line 14

def initialize
  @base_url = 'https://api.emailable.com/v1'
  @connection = create_connection(URI(@base_url))
end

Instance Method Details

#request(method, endpoint, params = {}) ⇒ Object

Raises:

  • ()


19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/emailable/client.rb', line 19

def request(method, endpoint, params = {})
  begin
    tries ||= 3

    uri = URI("#{@base_url}/#{endpoint}")
    params[:api_key] = Emailable.api_key

    http_response =
      if method == :get
        uri.query = URI.encode_www_form(params)
        @connection.get(uri)
      elsif method == :post
        request = Net::HTTP::Post.new(uri, 'Content-Type': 'application/json')
        request.body = params.to_json
        @connection.request(request)
      end

    response = Response.new(http_response)
  rescue => e
    retry if (tries -= 1) > 0 && self.class.should_retry?(e, tries)

    raise e
  end

  status = response.status
  return response if status.between?(200, 299)

  raise ERRORS[status].new(response.body['message'])
end