Class: HostradoAPI::V1::Connection

Inherits:
Object
  • Object
show all
Defined in:
lib/v1/connection.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(token, api_server = nil) ⇒ Connection



8
9
10
11
12
13
# File 'lib/v1/connection.rb', line 8

def initialize(token, api_server = nil)
  @token = token
  @api_server = api_server ? api_server : 'https://api.hostrado.com/v1'

  @domains = HostradoAPI::V1::Domains.new(self)
end

Instance Attribute Details

#api_serverObject (readonly)

Returns the value of attribute api_server.



5
6
7
# File 'lib/v1/connection.rb', line 5

def api_server
  @api_server
end

#domainsObject

Returns the value of attribute domains.



6
7
8
# File 'lib/v1/connection.rb', line 6

def domains
  @domains
end

#tokenObject (readonly)

Returns the value of attribute token.



4
5
6
# File 'lib/v1/connection.rb', line 4

def token
  @token
end

Instance Method Details

#send_request(method, path, params = {}) ⇒ Object



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/v1/connection.rb', line 15

def send_request(method, path, params = {})
  timeout = params[:timeout] ? params[:timeout].to_i : 10
  params.delete(:timeout)

  uri = URI("#{@api_server}/#{path}")

  request_params = format_params(params) unless format_params(params).empty?

  begin
    request = Net::HTTP.start(uri.host, uri.port, use_ssl: (uri.scheme == 'https'), open_timeout: timeout)
    response = request.send_request(method.to_s.upcase, uri.path.empty? ? '/' : uri.path, request_params, { 'X-Hostrado-Token': @token })

    raise RemoteInternalServerError.new(response.body) if response.code == '500'

    response_body = JSON.parse(response.body)

    raise InvalidAccessTokenError.new(response_body['message']) if response.code == '401' && response_body['error'] == 'invalid_api_token'
    raise HostradoAPIError.new(response.body) unless response.code == '200'

    [response_body, response]
  rescue Errno::ECONNREFUSED, SocketError, Net::OpenTimeout => err
    raise ConnectionError.new(err.to_s)
  rescue JSON::ParserError => err
    raise ResponseFormatError.new("API server sent a non-JSON string: #{response.body}")
  end
end