lib/ezclient/request.rb in ezclient-0.9.1 vs lib/ezclient/request.rb in ezclient-0.10.0

- old
+ new

@@ -1,14 +1,25 @@ # frozen_string_literal: true class EzClient::Request + OPTION_KEYS = %i[ + body + form + json + metadata + params + query + ].freeze + attr_accessor :verb, :url, :options def initialize(verb, url, options) self.verb = verb.to_s.upcase self.url = url + self.client = options.delete(:client) self.options = options + EzClient::CheckOptions.call(options, OPTION_KEYS + EzClient::Client::REQUEST_OPTION_KEYS) end def perform http_response = perform_request @@ -51,10 +62,12 @@ @http_options ||= http_client.default_options.merge(ssl_context: options[:ssl_context]) end private + attr_accessor :client + def http_request @http_request ||= begin # RUBY25: Hash#slice opts = options.select { |key| [:json, :body, :headers].include?(key) } opts[verb == "GET" ? :params : :form] = options[:params] @@ -66,28 +79,29 @@ end def http_client # Only used to build proper HTTP::Request and HTTP::Options instances @http_client ||= begin - client = options[:client].dup - client = client.timeout(timeout) if timeout - client = client.basic_auth(basic_auth) if basic_auth - client + http_client = client.dup + http_client = http_client.timeout(timeout) if timeout + http_client = http_client.basic_auth(basic_auth) if basic_auth + http_client end end def perform_request retries = 0 begin retry_on_connection_error do - client = options.fetch(:client) # Use original client so that connection can be reused + # Use original client so that connection can be reused client.perform(http_request, http_options) end - rescue *retried_exceptions + rescue *retried_exceptions => error if retries < max_retries.to_i retries += 1 + on_retry.call(self, error, options[:metadata]) retry else raise end end @@ -95,11 +109,12 @@ def retry_on_connection_error # This may result in 2 requests reaching the server so I hope HTTP fixes it # https://github.com/httprb/http/issues/459 yield - rescue HTTP::ConnectionError + rescue HTTP::ConnectionError => error + on_retry.call(self, error, options[:metadata]) yield end def timeout options[:timeout]&.to_f @@ -109,9 +124,13 @@ options[:on_complete] || proc {} end def on_error options[:on_error] || proc {} + end + + def on_retry + options[:on_retry] || proc {} end def retried_exceptions Array(options[:retry_exceptions]) end