lib/manageiq/api/client/connection.rb in manageiq-api-client-0.4.0 vs lib/manageiq/api/client/connection.rb in manageiq-api-client-0.6.0
- old
+ new
@@ -1,17 +1,19 @@
module ManageIQ
module API
class Client
class Connection
+ extend Forwardable
+
attr_reader :url
attr_reader :authentication
attr_reader :client
attr_reader :connection_options
attr_reader :response
attr_reader :error
- delegate :url, :authentication, :to => :client
+ def_delegators :client, :url, :authentication
API_PREFIX = "/api".freeze
CONTENT_TYPE = "application/json".freeze
def initialize(client, connection_options = {})
@@ -56,30 +58,37 @@
rescue
raise JSON::ParserError, "Response received from #{url} is not of type #{CONTENT_TYPE}"
end
def api_path(path)
- if path.to_s.starts_with?(url.to_s)
+ if path.to_s.start_with?(url.to_s)
path.to_s
elsif path.to_s.blank?
URI.join(url, API_PREFIX).to_s
else
- URI.join(url, path.to_s.starts_with?(API_PREFIX) ? path.to_s : "#{API_PREFIX}/#{path}").to_s
+ URI.join(url, path.to_s.start_with?(API_PREFIX) ? path.to_s : "#{API_PREFIX}/#{path}").to_s
end
end
def handle
ssl_options = @connection_options[:ssl]
Faraday.new(:url => url, :ssl => ssl_options) do |faraday|
faraday.request(:url_encoded) # form-encode POST params
faraday.options.open_timeout = @connection_options[:open_timeout] if @connection_options[:open_timeout]
faraday.options.timeout = @connection_options[:timeout] if @connection_options[:timeout]
faraday.response(:logger, client.logger)
- faraday.use FaradayMiddleware::FollowRedirects, :limit => 3, :standards_compliant => true
- faraday.adapter(Faraday.default_adapter) # make requests with Net::HTTP
+ faraday.response(:follow_redirects, :limit => 3, :standards_compliant => true)
+ # make requests with Net::HTTP
+ faraday.adapter(Faraday.default_adapter)
if authentication.token.blank? && authentication.miqtoken.blank? && authentication.bearer_token.blank?
- faraday.basic_auth(authentication.user, authentication.password)
+ if faraday.respond_to?(:basic_auth)
+ # faraday 1.0
+ faraday.basic_auth(authentication.user, authentication.password)
+ else
+ # faraday 2.0
+ faraday.request(:authorization, :basic, authentication.user, authentication.password)
+ end
end
end
end
private
@@ -103,14 +112,14 @@
check_response
end
def check_response
if response.status == 404
- message = json_response.fetch_path("error", "message") || json_response["error"]
+ message = json_response["error"].kind_of?(String) ? json_response["error"] : json_response.dig("error", "message")
raise ManageIQ::API::Client::ResourceNotFound, message
elsif response.status >= 400
@error = ManageIQ::API::Client::Error.new(response.status, json_response)
- raise @error.message
+ raise ManageIQ::API::Client::Exception, @error.message || "Empty Response"
end
end
end
end
end