Class: CreditGateway::Client

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

Instance Method Summary collapse

Constructor Details

#initializeClient

Returns a new instance of Client.



11
12
13
14
15
# File 'lib/credit_gateway/client.rb', line 11

def initialize
  return if Faraday::Request.fetch_middleware(:credit_gateway_auth)

  Faraday::Request.register_middleware credit_gateway_auth: -> { CreditGateway::FaradayAuth }
end

Instance Method Details

#api_urlObject



43
44
45
# File 'lib/credit_gateway/client.rb', line 43

def api_url
  CreditGateway.configuration.base_url
end

#connectionObject



29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/credit_gateway/client.rb', line 29

def connection
  @connection ||= Faraday.new(url: api_url) do |conn|
    conn.request :credit_gateway_auth,
                 CreditGateway.configuration.client_id,
                 CreditGateway.configuration.client_secret,
                 CreditGateway.configuration.country
    conn.response :multi_json, symbolize_keys: true
    if CreditGateway.configuration.debug
      conn.response :logger, nil, { headers: true, bodies: CreditGateway.configuration.verbose }
    end
    conn.adapter Faraday.default_adapter
  end
end

#get(path, headers: {}, params: {}) ⇒ Object



17
18
19
20
21
# File 'lib/credit_gateway/client.rb', line 17

def get(path, headers: {}, params: {})
  connection.get(path, params, headers).tap do |response|
    handle_response(response)
  end
end

#handle_company_not_found(body, alternative_exception) ⇒ Object



64
65
66
67
68
# File 'lib/credit_gateway/client.rb', line 64

def handle_company_not_found(body, alternative_exception)
  raise CompanyNotFoundError, body.dig(0, :message) if body.dig(0, :code) == 'company_not_found'

  raise alternative_exception, body
end

#handle_response(response) ⇒ Object



47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/credit_gateway/client.rb', line 47

def handle_response(response)
  return if response.success?

  case response.status
  when 400
    handle_company_not_found(response.body, InvalidRequestError)
  when 401
    raise UnauthorizedError, response.body
  when 404
    handle_company_not_found(response.body, NotFoundError)
  when 409
    raise ConflictError, response.body
  else
    raise GenericError, "#{response.status}: #{response.body}"
  end
end

#post(path, headers: {}, params: {}) ⇒ Object



23
24
25
26
27
# File 'lib/credit_gateway/client.rb', line 23

def post(path, headers: {}, params: {})
  connection.post(path, MultiJson.dump(params), headers).tap do |response|
    handle_response(response)
  end
end