Class: NRQL2Nerd::Client

Inherits:
Object
  • Object
show all
Defined in:
lib/nrql2nerd/client.rb

Instance Method Summary collapse

Constructor Details

#initialize(api_key: nil, account_id: nil) ⇒ Client

Returns a new instance of Client.



7
8
9
10
11
12
13
# File 'lib/nrql2nerd/client.rb', line 7

def initialize(api_key: nil, account_id: nil)
  @api_key = ENV.fetch("NEW_RELIC_API_KEY", api_key)
  @account_id = ENV.fetch("NEW_RELIC_ACCOUNT_ID", )

  raise "NEW_RELIC_API_KEY is not set" if @api_key.nil?
  raise "NEW_RELIC_ACCOUNT_ID is not set" if @account_id.nil?
end

Instance Method Details

#clientObject



39
40
41
42
43
44
# File 'lib/nrql2nerd/client.rb', line 39

def client
  http = Net::HTTP.new(uri.host, uri.port)
  http.use_ssl = true

  http
end

#graphql_hash(query) ⇒ Object



29
30
31
32
33
# File 'lib/nrql2nerd/client.rb', line 29

def graphql_hash(query)
  {
    query: graphql_nrql_query(query)
  }
end

#graphql_nrql_query(query) ⇒ Object



15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/nrql2nerd/client.rb', line 15

def graphql_nrql_query(query)
  <<~GRAPHQL
      query {
        actor {
          account(id: #{@account_id}) {
          nrql(query: "#{query}") {
            results
          }
        }
      }
    }
  GRAPHQL
end

#make_query_request(query) ⇒ Object



50
51
52
53
54
55
56
57
# File 'lib/nrql2nerd/client.rb', line 50

def make_query_request(query)
  request = Net::HTTP::Post.new(uri)
  request["Content-Type"] = "application/json"
  request["API-Key"] = @api_key
  request.body = prepare_query(query)

  client.request(request)
end

#prepare_query(query) ⇒ Object



35
36
37
# File 'lib/nrql2nerd/client.rb', line 35

def prepare_query(query)
  JSON.pretty_generate(graphql_hash(query))
end

#run_query(query) ⇒ Object



59
60
61
62
63
# File 'lib/nrql2nerd/client.rb', line 59

def run_query(query)
  response = make_query_request(query)

  JSON.parse(response.body).dig("data", "actor", "account", "nrql", "results")
end

#uriObject



46
47
48
# File 'lib/nrql2nerd/client.rb', line 46

def uri
  URI("https://api.newrelic.com/graphql")
end