Class: ControlplaneApiDirect
- Inherits:
-
Object
- Object
- ControlplaneApiDirect
- Defined in:
- lib/core/controlplane_api_direct.rb
Constant Summary collapse
- API_METHODS =
{ get: Net::HTTP::Get, 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
-
#call(url, method:, host: :api) ⇒ Object
rubocop:disable Metrics/MethodLength.
Instance Method Details
#api_token ⇒ Object
34 35 36 37 38 39 40 41 42 |
# File 'lib/core/controlplane_api_direct.rb', line 34 def api_token return @@api_token if defined?(@@api_token) @@api_token = ENV.fetch("CPLN_TOKEN", `cpln profile token`.chomp) # rubocop:disable Style/ClassVars 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) ⇒ Object
rubocop:disable Metrics/MethodLength
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
# File 'lib/core/controlplane_api_direct.rb', line 14 def call(url, method:, host: :api) # 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 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 |