Class: CreditGateway::Client

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

Instance Method Summary collapse

Instance Method Details

#api_urlObject



37
38
39
# File 'lib/credit_gateway/client.rb', line 37

def api_url
  CreditGateway.configuration.base_url
end

#connectionObject



23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/credit_gateway/client.rb', line 23

def connection
  @connection ||= Faraday.new(url: api_url) do |conn|
    conn.use CreditGateway::FaradayAuth,
             CreditGateway.configuration.client_id,
             CreditGateway.configuration.client_secret,
             CreditGateway.configuration.country
    conn.response :json, parser_options: { symbolize_names: 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



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

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



58
59
60
61
62
# File 'lib/credit_gateway/client.rb', line 58

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



41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/credit_gateway/client.rb', line 41

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



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

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