Class: TerraformEnterprise::API::Request

Inherits:
Object
  • Object
show all
Defined in:
lib/terraform-enterprise/client/request.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(api_key:, host: 'https://app.terraform.io/api/v2', debug: false) ⇒ Request

Returns a new instance of Request.



8
9
10
11
12
13
14
15
16
# File 'lib/terraform-enterprise/client/request.rb', line 8

def initialize(api_key:, host: 'https://app.terraform.io/api/v2', debug: false)
  @base    = host
  @api_key = api_key
  @debug   = debug
  @headers = {
    'Authorization' => "Bearer #{@api_key}",
    'Content-Type' => 'application/vnd.api+json'
  }
end

Instance Attribute Details

#baseObject

Returns the value of attribute base.



6
7
8
# File 'lib/terraform-enterprise/client/request.rb', line 6

def base
  @base
end

Instance Method Details

#delete(*path) ⇒ Object



23
24
25
26
# File 'lib/terraform-enterprise/client/request.rb', line 23

def delete(*path)
  data = path.pop if path.last.is_a?(Hash)
  request(:delete, path,data)
end

#get(*path) ⇒ Object



18
19
20
21
# File 'lib/terraform-enterprise/client/request.rb', line 18

def get(*path)
  data = path.pop if path.last.is_a?(Hash)
  request(:get, path, data)
end

#patch(*path) ⇒ Object



38
39
40
41
# File 'lib/terraform-enterprise/client/request.rb', line 38

def patch(*path)
  data = path.pop if path.last.is_a?(Hash)
  request(:patch,path,data)
end

#post(*path) ⇒ Object



28
29
30
31
# File 'lib/terraform-enterprise/client/request.rb', line 28

def post(*path)
  data = path.pop if path.last.is_a?(Hash)
  request(:post, path, data)
end

#put(*path) ⇒ Object



33
34
35
36
# File 'lib/terraform-enterprise/client/request.rb', line 33

def put(*path)
  data = path.pop if path.last.is_a?(Hash)
  request(:put,data,data)
end

#request(method, path, data = {}, headers = {}) ⇒ Object



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/terraform-enterprise/client/request.rb', line 43

def request(method, path, data={}, headers={})
  request = {
    method:  method,
    url:     uri(path),
    headers: @headers.merge(headers || {})
  }
  if data
    if method==:get || method==:delete
      request[:headers][:params] = data
    else
      request[:payload] = data.is_a?(String) ? data : data.to_json
    end
  end

  response = begin
    RestClient::Request.execute(request)
  rescue RestClient::ExceptionWithResponse => ex
    ex.response
  end

  if @debug
    puts "[DEBUG] [REQUEST:METHOD]  #{request[:method].to_s.upcase} #{request[:url]}"
    puts "[DEBUG] [REQUEST:HEADERS] #{request[:headers]}"
    puts "[DEBUG] [REQUEST:PAYLOAD] #{data}"
    puts "[DEBUG] [RESPONSE:CODE]   #{response.code}" 
    puts "[DEBUG] [RESPONSE:BODY]   #{response.body}" 
  end

  TerraformEnterprise::API::Response.new(response)
end