Class: Mackerel::ApiCommand
- Inherits:
-
Object
- Object
- Mackerel::ApiCommand
- Defined in:
- lib/mackerel/api_command.rb
Constant Summary collapse
- METHODS =
[:get, :delete, :put, :post]
- JSON_CONTENT_TYPE =
'application/json'
Instance Attribute Summary collapse
-
#body ⇒ Object
Returns the value of attribute body.
-
#headers ⇒ Object
Returns the value of attribute headers.
-
#params ⇒ Object
Returns the value of attribute params.
-
#query ⇒ Object
Returns the value of attribute query.
Instance Method Summary collapse
- #execute(client) ⇒ Object
-
#initialize(method, path, api_key) ⇒ ApiCommand
constructor
A new instance of ApiCommand.
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
#body ⇒ Object
Returns the value of attribute body.
9 10 11 |
# File 'lib/mackerel/api_command.rb', line 9 def body @body end |
#headers ⇒ Object
Returns the value of attribute headers.
9 10 11 |
# File 'lib/mackerel/api_command.rb', line 9 def headers @headers end |
#params ⇒ Object
Returns the value of attribute params.
9 10 11 |
# File 'lib/mackerel/api_command.rb', line 9 def params @params end |
#query ⇒ Object
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]) = body["error"].is_a?(Hash) ? body["error"]["message"] : body["error"] raise Mackerel::Error, "#{@method.upcase} #{@path} failed: #{e.response[:status]} #{}" 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 |