Class: VagrantPlugins::SimpleCloud::Helpers::ApiClientService

Inherits:
Object
  • Object
show all
Defined in:
lib/vagrant-simple_cloud/helpers/client_service.rb

Instance Method Summary collapse

Constructor Details

#initialize(machine) ⇒ ApiClientService

Returns a new instance of ApiClientService.



16
17
18
19
20
21
22
23
24
25
# File 'lib/vagrant-simple_cloud/helpers/client_service.rb', line 16

def initialize(machine)
  @logger = Log4r::Logger.new('vagrant::simple_cloud::apiclientservice')
  @config = machine.provider_config
  @clientservice = Faraday.new({
    :url => @config.serviceaddr,
    :ssl => {
      :ca_file => @config.ca_path
    }
  })
end

Instance Method Details

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



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
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/vagrant-simple_cloud/helpers/client_service.rb', line 27

def post(path, params = {}, method = :post)
  @clientservice.headers['Content-Type'] = 'application/json'
  begin
    @logger.info "Request: #{path}"
    result = @clientservice.send(method) do |req|
      req.url path
      req.headers['Authorization'] = "#{@config.token}"
      req.body = params.to_json
    end
  rescue Faraday::Error::ConnectionFailed => e
    # TODO this is suspect but because farady wraps the exception
    #      in something generic there doesn't appear to be another
    #      way to distinguish different connection errors :(
    if e.message =~ /certificate verify failed/
      raise Errors::CertificateError
    end

    raise e
  end

  begin
    body = JSON.parse(result.body)
    @logger.info "Response: #{body}"
    next_page = body["links"]["pages"]["next"] rescue nil
    unless next_page.nil?
      uri = URI.parse(next_page)
      new_path = path.split("?")[0]
      next_result = self.request("#{new_path}?#{uri.query}")
      req_target = new_path.split("/")[-1]
      body["#{req_target}"].concat(next_result["#{req_target}"])
    end
  rescue JSON::ParserError => e
    raise(Errors::JSONError, {
      :message => e.message,
      :path => path,
      :params => params,
      :response => result.body
    })
  end

  unless /^2\d\d$/ =~ result.status.to_s
    raise(Errors::APIStatusError, {
      :path => path,
      :params => params,
      :status => result.status,
      :response => body.inspect
    })
  end

  Result.new(body)
end