Class: ControlplaneApiDirect
- Inherits:
-
Object
- Object
- ControlplaneApiDirect
- Defined in:
- lib/core/controlplane_api_direct.rb
Constant Summary collapse
- API_METHODS =
{ get: Net::HTTP::Get, patch: Net::HTTP::Patch, post: Net::HTTP::Post, put: Net::HTTP::Put, delete: Net::HTTP::Delete }.freeze
- API_HOSTS =
{ api: "https://api.cpln.io", logs: "https://logs.cpln.io" }.freeze
- API_TOKEN_REGEX =
API_TOKEN_REGEX = Regexp.union(
/^[\w.]{155}$/, # CPLN_TOKEN format /^[\w\-._]{1134}$/ # 'cpln profile token' format).freeze
/^[\w\-._]+$/.freeze
Instance Method Summary collapse
-
#api_token ⇒ Object
rubocop:disable Style/ClassVars.
-
#call(url, method:, host: :api, body: nil) ⇒ Object
rubocop:disable Metrics/MethodLength.
Instance Method Details
#api_token ⇒ Object
rubocop:disable Style/ClassVars
42 43 44 45 46 47 48 49 50 51 |
# File 'lib/core/controlplane_api_direct.rb', line 42 def api_token return @@api_token if defined?(@@api_token) @@api_token = ENV.fetch("CPLN_TOKEN", nil) @@api_token = `cpln profile token`.chomp if @@api_token.nil? return @@api_token if @@api_token.match?(API_TOKEN_REGEX) raise "Unknown API token format. " \ "Please re-run 'cpln profile login' or set the correct CPLN_TOKEN env variable." end |
#call(url, method:, host: :api, body: nil) ⇒ Object
rubocop:disable Metrics/MethodLength
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
# File 'lib/core/controlplane_api_direct.rb', line 20 def call(url, method:, host: :api, body: nil) # rubocop:disable Metrics/MethodLength uri = URI("#{API_HOSTS[host]}#{url}") request = API_METHODS[method].new(uri) request["Content-Type"] = "application/json" request["Authorization"] = api_token request.body = body.to_json if body response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) { |http| http.request(request) } case response when Net::HTTPOK JSON.parse(response.body) when Net::HTTPAccepted true when Net::HTTPNotFound nil else raise("#{response} #{response.body}") end end |