Class: Mackerel::ApiCommand

Inherits:
Object
  • Object
show all
Defined in:
lib/mackerel/api_command.rb

Constant Summary collapse

METHODS =
[:get, :delete, :put, :post]
JSON_CONTENT_TYPE =
'application/json'

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(method, path, api_key) ⇒ ApiCommand

Returns a new instance of ApiCommand.



11
12
13
14
15
16
17
18
19
20
# File 'lib/mackerel/api_command.rb', line 11

def initialize(method, path, api_key)
  @path = path
  @method = method
  @api_key = api_key

  @headers = {}
  @body = ''
  @params = {}
  @query = {}
end

Instance Attribute Details

#bodyObject

Returns the value of attribute body.



9
10
11
# File 'lib/mackerel/api_command.rb', line 9

def body
  @body
end

#headersObject

Returns the value of attribute headers.



9
10
11
# File 'lib/mackerel/api_command.rb', line 9

def headers
  @headers
end

#paramsObject

Returns the value of attribute params.



9
10
11
# File 'lib/mackerel/api_command.rb', line 9

def params
  @params
end

#queryObject

Returns the value of attribute query.



9
10
11
# File 'lib/mackerel/api_command.rb', line 9

def query
  @query
end

Instance Method Details

#execute(client) ⇒ Object



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
# File 'lib/mackerel/api_command.rb', line 22

def execute(client)
  return unless METHODS.include?(@method)

  request_path = @path
  request_path << "?#{make_escaped_query}" if @query.any?

  client_method = client.method(@method)
  response = client_method.call(request_path) do |req|
    req.headers.update @headers
    req.headers['x-api-key'] = @api_key
    req.headers['Content-Type'] ||= JSON_CONTENT_TYPE
    req.params = @params
    req.body = @body
  end
  JSON.parse(response.body)
rescue Faraday::ClientError, Faraday::ServerError => e
  begin
    body = JSON.parse(e.response[:body])
    message = body["error"].is_a?(Hash) ? body["error"]["message"] : body["error"]
    raise Mackerel::Error, "#{@method.upcase} #{@path} failed: #{e.response[:status]} #{message}"
  rescue JSON::ParserError
    # raise Mackerel::Error with original response body
    raise Mackerel::Error, "#{@method.upcase} #{@path} failed: #{e.response[:status]} #{e.response[:body]}"
  end
end