Class: BlazeVerify::Client

Inherits:
Object
  • Object
show all
Defined in:
lib/blazeverify/client.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeClient

Returns a new instance of Client.



4
5
6
7
8
9
10
# File 'lib/blazeverify/client.rb', line 4

def initialize
  @client = Faraday.new('https://api.blazeverify.com/v1') do |f|
    f.request :url_encoded
    f.response :json, content_type: /\bjson$/
    f.adapter :net_http_persistent
  end
end

Class Method Details

.should_retry?(error, num_retries) ⇒ Boolean

Returns:

  • (Boolean)


51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/blazeverify/client.rb', line 51

def self.should_retry?(error, num_retries)
  return false if num_retries >= BlazeVerify.max_network_retries

  # Retry on timeout-related problems (either on open or read).
  return true if error.is_a?(Faraday::TimeoutError)

  # Destination refused the connection, the connection was reset, or a
  # variety of other connection failures. This could occur from a single
  # saturated server, so retry in case it's intermittent.
  return true if error.is_a?(Faraday::ConnectionFailed)

  if error.is_a?(Faraday::ClientError) && error.response
    # 409 conflict
    return true if error.response[:status] == 409
  end

  false
end

Instance Method Details

#request(method, endpoint, opts = {}) ⇒ Object

Raises:

  • ()


12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/blazeverify/client.rb', line 12

def request(method, endpoint, opts = {})
  begin
    tries ||= 0

    @client.params[:api_key] = BlazeVerify.api_key

    response =
      if method == :get
        @client.get(endpoint, opts)
      elsif method == :post
        @client.post(endpoint, opts)
      end
  rescue => e
    retry if self.class.should_retry?(e, tries)

    raise e
  end

  status = response.status
  return response if status.between?(200, 299)

  error_attributes = {
    message: response.body['message'],
    code: status
  }
  error_map = {
    '400' => BadRequestError,
    '401' => UnauthorizedError,
    '402' => PaymentRequiredError,
    '403' => ForbiddenError,
    '404' => NotFoundError,
    '429' => TooManyRequestsError,
    '500' => InternalServerError,
    '503' => ServiceUnavailableError
  }

  raise error_map[status.to_s].new(error_attributes)
end