class DogapiDemo::APIService

Superclass that deals with the details of communicating with the DataDog API

Public Class Methods

new(api_key, application_key, silent=true, timeout=nil) click to toggle source
   # File lib/dogapi-demo/common.rb
72 def initialize(api_key, application_key, silent=true, timeout=nil)
73   @api_key = api_key
74   @application_key = application_key
75   @api_host = DogapiDemo.find_datadog_host()
76   @silent = silent
77   @timeout = timeout || 5
78 end

Public Instance Methods

connect() { |conn| ... } click to toggle source

Manages the HTTP connection

    # File lib/dogapi-demo/common.rb
 81 def connect
 82   connection = Net::HTTP
 83 
 84   # After ruby 2.0 Net::HTTP looks for the env variable but not ruby 1.9
 85   if RUBY_VERSION < "2.0.0"
 86     proxy = ENV["HTTPS_PROXY"] || ENV["https_proxy"] || ENV["HTTP_PROXY"] || ENV["http_proxy"]
 87     if proxy
 88       proxy_uri = URI.parse(proxy)
 89       connection = Net::HTTP::Proxy(proxy_uri.host, proxy_uri.port, proxy_uri.user, proxy_uri.password)
 90     end
 91   end
 92 
 93   uri = URI.parse(@api_host)
 94   session = connection.new(uri.host, uri.port)
 95   session.open_timeout = @timeout
 96   session.use_ssl = uri.scheme == 'https'
 97   session.start do |conn|
 98     conn.read_timeout = @timeout
 99     yield(conn)
100   end
101 end
request(method, url, params, body, send_json) click to toggle source

Prepares the request and handles the response

method is an implementation of Net::HTTP::Request (e.g. Net::HTTP::Post)

params is a Hash that will be converted to request parameters

    # File lib/dogapi-demo/common.rb
117 def request(method, url, params, body, send_json)
118   resp_obj = nil
119   resp = nil
120   connect do |conn|
121     if params and params.size > 0
122       qs_params = params.map { |k, v| k.to_s + "=" + v.to_s }
123       qs = "?" + qs_params.join("&")
124       url = url + qs
125     end
126 
127     req = method.new(url)
128 
129     if send_json
130       req.content_type = 'application/json'
131       req.body = MultiJson.dump(body)
132     end
133 
134     resp = conn.request(req)
135     resp_str = resp.body
136 
137     if resp.code != 204 and resp.body != '' and resp.body != 'null' and resp.body != nil
138       begin
139         resp_obj = MultiJson.load(resp.body)
140       rescue
141         raise 'Invalid JSON Response: ' + resp.body
142       end
143     else
144       resp_obj = {}
145     end
146   end
147   return resp.code, resp_obj
148 end
suppress_error_if_silent(e) click to toggle source
    # File lib/dogapi-demo/common.rb
103 def suppress_error_if_silent(e)
104   if @silent
105     warn e
106     return -1, {}
107   else
108     raise e
109   end
110 end