Module: Legion::CLI::ApiClient

Defined in:
lib/legion/cli/api_client.rb

Overview

Shared HTTP client for CLI commands that talk to the running daemon API. Include this module inside a Thor command’s ‘no_commands` block, or extend it at the class level, to get api_get / api_post / api_put / api_delete helpers that target 127.0.0.1:<port>/api/*.

Instance Method Summary collapse

Instance Method Details

#api_delete(path) ⇒ Object



65
66
67
68
69
70
71
72
73
74
75
76
# File 'lib/legion/cli/api_client.rb', line 65

def api_delete(path)
  uri = URI("http://127.0.0.1:#{api_port}#{path}")
  http = build_http(uri)
  response = http.delete(uri.path)
  handle_response(response, path)
rescue Errno::ECONNREFUSED
  daemon_not_running!
rescue SystemExit
  raise
rescue StandardError => e
  api_error!(e, path)
end

#api_get(path) ⇒ Object



22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/legion/cli/api_client.rb', line 22

def api_get(path)
  uri = URI("http://127.0.0.1:#{api_port}#{path}")
  http = build_http(uri)
  response = http.get(uri.request_uri)
  handle_response(response, path)
rescue Errno::ECONNREFUSED
  daemon_not_running!
rescue SystemExit
  raise
rescue StandardError => e
  api_error!(e, path)
end

#api_portObject



14
15
16
17
18
19
20
# File 'lib/legion/cli/api_client.rb', line 14

def api_port
  Connection.ensure_settings
  api_settings = Legion::Settings[:api]
  (api_settings.is_a?(Hash) && api_settings[:port]) || 4567
rescue StandardError
  4567
end

#api_post(path, **payload) ⇒ Object



35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/legion/cli/api_client.rb', line 35

def api_post(path, **payload)
  uri = URI("http://127.0.0.1:#{api_port}#{path}")
  http = build_http(uri, read_timeout: 300)
  request = Net::HTTP::Post.new(uri.path, 'Content-Type' => 'application/json')
  request.body = ::JSON.generate(payload)
  response = http.request(request)
  handle_response(response, path)
rescue Errno::ECONNREFUSED
  daemon_not_running!
rescue SystemExit
  raise
rescue StandardError => e
  api_error!(e, path)
end

#api_put(path, **payload) ⇒ Object



50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/legion/cli/api_client.rb', line 50

def api_put(path, **payload)
  uri = URI("http://127.0.0.1:#{api_port}#{path}")
  http = build_http(uri)
  request = Net::HTTP::Put.new(uri.path, 'Content-Type' => 'application/json')
  request.body = ::JSON.generate(payload)
  response = http.request(request)
  handle_response(response, path)
rescue Errno::ECONNREFUSED
  daemon_not_running!
rescue SystemExit
  raise
rescue StandardError => e
  api_error!(e, path)
end