lib/nano_rpc/client.rb in nano_rpc-0.5.0 vs lib/nano_rpc/client.rb in nano_rpc-0.6.0

- old
+ new

@@ -8,15 +8,17 @@ end class Client include Nano::ApplicationHelper - attr_accessor :host, :port + attr_reader :host, :port, :auth, :headers - def initialize(host: 'localhost', port: 7076) + def initialize(host: 'localhost', port: 7076, auth: nil, headers: nil) @host = host @port = port + @auth = auth + @headers = headers end # Condense host/port on object inspection def inspect "#{inspect_prefix}, @url=\"#{@host}:#{port}\">" @@ -51,33 +53,44 @@ def rpc_post(params) response = rest_client_post(url, params) ensure_status_success!(response) - data = Nano::Response.new(JSON[response.body]) + data = Nano::Response.new(JSON[response&.body]) ensure_valid_response!(data) data end + def request_headers + h = headers || {} + h['Content-Type'] = 'json' + h['Authorization'] = auth unless auth.nil? + h + end + def rest_client_post(url, params) - RestClient.post(url, params.to_json) + RestClient.post(url, params, request_headers) rescue Errno::ECONNREFUSED raise Nano::NodeConnectionFailure, "Node connection failure at #{url}" rescue RestClient::Exceptions::OpenTimeout raise Nano::NodeOpenTimeout, 'Node failed to respond in time' end def url - "http://#{host}:#{port}" + if host.start_with?('http://', 'https://') + "#{host}:#{port}" + else + "http://#{host}:#{port}" + end end def ensure_status_success!(response) - return if response.code == 200 + return if response&.code == 200 raise Nano::BadRequest, - "Error response from node: #{JSON[response.body]}" + "Error response from node: #{JSON[response&.body]}" end def ensure_valid_response!(data) return unless data['error'] raise Nano::InvalidRequest,