Puppet Function: graphql::graphql_query

Defined in:
lib/puppet/functions/graphql/graphql_query.rb
Function type:
Ruby 4.x API

Overview

graphql::graphql_query(Hash[String[1], Any] $opts)Optional[Hash]

Query a GraphQL API via HTTP.

Parameters:

  • opts (Hash[String[1], Any])

    A Hash with the keys ‘url` (value `String`), `headers` (value `Hash`) and query (value `String`).

Returns:

  • (Optional[Hash])

    A hash containing the response data or nil when an error occurred.



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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
47
48
# File 'lib/puppet/functions/graphql/graphql_query.rb', line 6

Puppet::Functions.create_function(:"graphql::graphql_query") do
  # @param opts A Hash with the keys `url` (value `String`), `headers` (value `Hash`) and query (value `String`).
  # @return A hash containing the response data or nil when an error occurred.
  dispatch :graphql_query do
    param 'Hash[String[1], Any]', :opts
    return_type 'Optional[Hash]'
  end

  def graphql_query(opts)
    url = get_opt(opts, 'url')
    headers = get_opt(opts, 'headers')
    query = get_opt(opts, 'query')

    Puppet.info "graphql::graphql_query: Querying #{url}"

    begin
      uri = URI(url)
      request_body = { 'query' => query, 'variables' => nil }.to_json
      request_headers = {
        'Content-Type' => 'application/json',
        'Accept' => 'application/json',
      }.merge(headers)
      response = Net::HTTP.post(uri, request_body, request_headers)
      unless response.is_a? Net::HTTPSuccess
        raise "Unexpected response code #{response.code}: #{response.body}"
      end
      JSON.parse(response.body)
    rescue => error
      puts error
      Puppet.err "graphql::graphql_query: #{error}!"
      call_function('create_resources', 'notify', { "graphql::graphql_query: #{error}!" => {} })
      nil
    end
  end

  def get_opt(opts, *path)
    opt = opts.dig(*path)
    if opt.nil?
      raise Puppet::ParseError, "Option #{path.join('.')} must be present in opts argument"
    end
    opt
  end
end