Class: Omie::Connection
- Inherits:
-
Object
- Object
- Omie::Connection
- Defined in:
- lib/omie/connection.rb
Overview
This class is used internally to send HTTP requests to Omie API based on RestClient gem. It is responsible for parsing JSON to Hash objects and handle errors.
Constant Summary collapse
- API_URI =
Base URL for Omie API
'https://app.omie.com.br/api'
Class Method Summary collapse
-
.create_payload(call, data = {}) ⇒ String
Create the payload of the request with the credentials, the specific call and the payload data.
-
.handle_error_with_response(response) ⇒ Object
Handle errors with a response from Omie API by raising custom exceptions.
-
.request(url, call, payload_to_request = {}) ⇒ Hash
Perform a request to Omie API based on params.
Class Method Details
.create_payload(call, data = {}) ⇒ String
Create the payload of the request with the credentials, the specific call and the payload data.
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 |
# File 'lib/omie/connection.rb', line 60 def self.create_payload(call, data = {}) if Omie.app_key.blank? || Omie.app_secret.blank? raise Omie::MissingCredentialsError, 'Omie.app_key and Omie.app_secret cannot be blank' end payload_request = { app_key: Omie.app_key, app_secret: Omie.app_secret, call: call, param: [data] } payload_request.to_json end |
.handle_error_with_response(response) ⇒ Object
Handle errors with a response from Omie API by raising custom exceptions. The API does not use the HTTP status codes appropriately since it always returns error 500 for all kind of known errors (client errors). Moreover, the specific details of the error are described in the returned JSON. See RequestError for more details.
88 89 90 91 92 |
# File 'lib/omie/connection.rb', line 88 def self.handle_error_with_response(response) raise Omie::RequestError.new(nil, response) if response.code == 500 raise Omie::InvalidResponseError, "Invalid response received: #{response}" end |
.request(url, call, payload_to_request = {}) ⇒ Hash
Perform a request to Omie API based on params. It does not make any kind of manipulation, and validation of such params. Rather, it only abstracts the interaction with the API, parsing the response or handling possible errors.
36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
# File 'lib/omie/connection.rb', line 36 def self.request(url, call, payload_to_request = {}) payload = create_payload(call, payload_to_request) response = RestClient::Request.new( method: :post, url: API_URI + url, payload: payload, headers: { content_type: :json } ).execute JSON.parse(response.body) rescue RestClient::ExceptionWithResponse => e Omie::Connection.handle_error_with_response(e.response) end |