module Jets::Gems::Api::Core

Public Instance Methods

build_request(klass, url, data={}) click to toggle source
# File lib/jets/gems/api/core.rb, line 13
def build_request(klass, url, data={})
  req = klass.new(url) # url includes query string and uri.path does not, must used url
  set_headers!(req)
  if [Net::HTTP::Delete, Net::HTTP::Patch, Net::HTTP::Post, Net::HTTP::Put].include?(klass)
    text = JSON.dump(data)
    req.body = text
    req.content_length = text.bytesize
  end
  req
end
delete(path, data={}) click to toggle source
# File lib/jets/gems/api/core.rb, line 77
def delete(path, data={})
  request(Net::HTTP::Delete, path, data)
end
get(path) click to toggle source
# File lib/jets/gems/api/core.rb, line 65
def get(path)
  request(Net::HTTP::Get, path)
end
http() click to toggle source
# File lib/jets/gems/api/core.rb, line 51
def http
  uri = URI(endpoint)
  http = Net::HTTP.new(uri.host, uri.port)
  http.open_timeout = http.read_timeout = 30
  http.use_ssl = true if uri.scheme == 'https'
  http
end
load_json(url, res) click to toggle source
# File lib/jets/gems/api/core.rb, line 33
def load_json(url, res)
  uri = URI(url)
  if ok?(res.code)
    JSON.load(res.body)
  else
    puts "Error: Non-successful http response status code: #{res.code}"
    puts "headers: #{res.each_header.to_h.inspect}"
    puts "ServerlessGems API #{url}" if ENV['SG_DEBUG']
    raise "ServerlessGems API called failed: #{uri.host}"
  end
end
ok?(http_code) click to toggle source

Note: 422 is Unprocessable Entity. This means an invalid data payload was sent. We want that to error and raise

# File lib/jets/gems/api/core.rb, line 47
def ok?(http_code)
  http_code =~ /^20/ || http_code =~ /^40/
end
patch(path, data={}) click to toggle source
# File lib/jets/gems/api/core.rb, line 73
def patch(path, data={})
  request(Net::HTTP::Patch, path, data)
end
post(path, data={}) click to toggle source
# File lib/jets/gems/api/core.rb, line 69
def post(path, data={})
  request(Net::HTTP::Post, path, data)
end
request(klass, path, data={}) click to toggle source

Always translate raw json response to ruby Hash

# File lib/jets/gems/api/core.rb, line 6
def request(klass, path, data={})
  url = url(path)
  req = build_request(klass, url, data)
  resp = http.request(req) # send request
  load_json(url, resp)
end
set_headers!(req) click to toggle source
# File lib/jets/gems/api/core.rb, line 24
def set_headers!(req)
  req['Authorization'] = token if token
  req['Content-Type'] = "application/vnd.api+json"
end
token() click to toggle source
# File lib/jets/gems/api/core.rb, line 29
def token
  Jets::Gems::Config.instance.data['key']
end
url(path) click to toggle source

API does not include the /. IE: app.terraform.io/api/v2

# File lib/jets/gems/api/core.rb, line 61
def url(path)
  "#{endpoint}/#{path}"
end