Class: Adminix::Helpers::NetHTTP
- Inherits:
-
Object
- Object
- Adminix::Helpers::NetHTTP
- Defined in:
- lib/adminix/helpers/net_http.rb
Class Method Summary collapse
- .default_headers ⇒ Object
- .get(path) ⇒ Object
- .post(path, payload) ⇒ Object
- .read_response_body(response) ⇒ Object
Class Method Details
.default_headers ⇒ Object
54 55 56 57 58 59 60 |
# File 'lib/adminix/helpers/net_http.rb', line 54 def self.default_headers [ ['Authorization', "Bearer #{Adminix.config.secret_key}"], ['X-Watcher-Version', Adminix::VERSION], ['Accept', 'application/json'] ] end |
.get(path) ⇒ Object
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
# File 'lib/adminix/helpers/net_http.rb', line 6 def self.get(path) uri = URI.parse("#{Adminix.config.api_host}/v1/#{path}") request = Net::HTTP::Get.new(uri) default_headers.each { |h| request[h[0]] = h[1] } opts = { use_ssl: uri.scheme == 'https' } response = Net::HTTP.start(uri.hostname, uri.port, opts) do |http| http.request(request) end read_response_body(response) rescue SocketError, Net::OpenTimeout, Net::ReadTimeout Adminix.logger.error("Can't connect to API") [false, nil] end |
.post(path, payload) ⇒ Object
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
# File 'lib/adminix/helpers/net_http.rb', line 22 def self.post(path, payload) uri = URI.parse("#{Adminix.config.api_host}/v1/#{path}") request = Net::HTTP::Post.new(uri) request.content_type = 'application/json' request.body = payload.to_json default_headers.each { |h| request[h[0]] = h[1] } opts = { use_ssl: uri.scheme == 'https' } response = Net::HTTP.start(uri.hostname, uri.port, opts) do |http| http.request(request) end read_response_body(response) rescue SocketError, Net::OpenTimeout, Net::ReadTimeout Adminix.logger.error("Can't connect to API") [false, nil] end |
.read_response_body(response) ⇒ Object
40 41 42 43 44 45 46 47 48 49 50 51 52 |
# File 'lib/adminix/helpers/net_http.rb', line 40 def self.read_response_body(response) unless response.is_a? Net::HTTPSuccess Adminix.logger.error("Received code #{response.code} from API") return [false, response.code] end data = JSON.parse(response.body) success = data['success'] || false result = data['result'] [success, result] end |