Module: Cloudpt::API::Connection::Requests

Included in:
Cloudpt::API::Connection
Defined in:
lib/cloudpt-api/connection/requests.rb

Instance Method Summary collapse

Instance Method Details

#get(endpoint, path, data = {}, headers = {}) ⇒ Object



44
45
46
47
48
49
50
51
# File 'lib/cloudpt-api/connection/requests.rb', line 44

def get(endpoint, path, data = {}, headers = {})
  query = Cloudpt::API::Util.query(data)
  query = "?#{URI.parse(URI.encode(query))}" unless query.empty?
  #puts "GET #{Cloudpt::API::Config.prefix}#{path}#{query}"
  request do
    token(endpoint).get "#{Cloudpt::API::Config.prefix}#{path}#{query}", headers
  end
end

#get_raw(endpoint, path, data = {}, headers = {}) ⇒ Object



36
37
38
39
40
41
42
# File 'lib/cloudpt-api/connection/requests.rb', line 36

def get_raw(endpoint, path, data = {}, headers = {})
  query = Cloudpt::API::Util.query(data)
  #puts "GET #{Cloudpt::API::Config.prefix}#{path}?#{URI.parse(URI.encode(query))}"
  request(:raw => true) do
    token(endpoint).get "#{Cloudpt::API::Config.prefix}#{path}?#{URI.parse(URI.encode(query))}", headers
  end
end

#post(endpoint, path, data = {}, headers = {}) ⇒ Object



53
54
55
56
57
58
59
# File 'lib/cloudpt-api/connection/requests.rb', line 53

def post(endpoint, path, data = {}, headers = {})
  #puts "POST #{Cloudpt::API::Config.prefix}#{path}"
  #puts "BODY:\n#{data}"
  request do
    token(endpoint).post "#{Cloudpt::API::Config.prefix}#{path}", data, headers
  end
end

#put(endpoint, path, data = {}, headers = {}) ⇒ Object



61
62
63
64
65
66
67
# File 'lib/cloudpt-api/connection/requests.rb', line 61

def put(endpoint, path, data = {}, headers = {})
  #puts "PUT #{Cloudpt::API::Config.prefix}#{path}"
  #puts "BODY:\n#{data}"
  request do
    token(endpoint).put "#{Cloudpt::API::Config.prefix}#{path}", data, headers
  end
end

#request(options = {}) ⇒ Object



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/cloudpt-api/connection/requests.rb', line 8

def request(options = {})
  response = yield
  raise Cloudpt::API::Error::ConnectionFailed if !response
  status = response.code.to_i
  #puts "STATUS:#{status}"
  #puts "PAYLOAD:\n#{response.body}"
  case status
    when 401
      raise Cloudpt::API::Error::Unauthorized
    when 403
      parsed = MultiJson.decode(response.body)
      raise Cloudpt::API::Error::Forbidden.new(parsed["error"])
    when 404
      raise Cloudpt::API::Error::NotFound
    when 400, 406
      parsed = MultiJson.decode(response.body)
      raise Cloudpt::API::Error.new(parsed["error"])
    when 300..399
      raise Cloudpt::API::Error::Redirect
    when 500..599
      raise Cloudpt::API::Error::ServerError
    else
      options[:raw] ? response.body : MultiJson.decode(response.body)
  end
end