Class: Bsale::APIBase
- Inherits:
-
Object
- Object
- Bsale::APIBase
- Defined in:
- lib/sale/base.rb
Direct Known Subclasses
Constant Summary collapse
- ENDPOINT =
'https://api.bsale.cl'.freeze
- VERSION =
'v1'.freeze
- MAX_RETRIES =
5
Instance Method Summary collapse
- #connect ⇒ Object
- #delete(path) ⇒ Object
- #disconnect ⇒ Object
- #get(path, params = nil) ⇒ Object
-
#initialize(token) ⇒ APIBase
constructor
A new instance of APIBase.
- #post(path, data) ⇒ Object
- #put(path, data) ⇒ Object
- #request(method, path, body = nil, attempt = 1) ⇒ Object
Constructor Details
#initialize(token) ⇒ APIBase
Returns a new instance of APIBase.
13 14 15 |
# File 'lib/sale/base.rb', line 13 def initialize(token) @token = token or raise 'Token not set!' end |
Instance Method Details
#connect ⇒ Object
56 57 58 |
# File 'lib/sale/base.rb', line 56 def connect @http ||= Dagger.open(ENDPOINT) end |
#delete(path) ⇒ Object
33 34 35 36 |
# File 'lib/sale/base.rb', line 33 def delete(path) resp = request(:delete, path) wrap_response(resp) end |
#disconnect ⇒ Object
60 61 62 63 |
# File 'lib/sale/base.rb', line 60 def disconnect @http.close if @http @http = nil end |
#get(path, params = nil) ⇒ Object
17 18 19 20 21 |
# File 'lib/sale/base.rb', line 17 def get(path, params = nil) path = params.nil? ? path : path + "?" + Dagger::Utils.encode(params) resp = request(:get, path) wrap_response(resp, params) end |
#post(path, data) ⇒ Object
23 24 25 26 |
# File 'lib/sale/base.rb', line 23 def post(path, data) resp = request(:post, path, data) wrap_response(resp) end |
#put(path, data) ⇒ Object
28 29 30 31 |
# File 'lib/sale/base.rb', line 28 def put(path, data) resp = request(:put, path, data) wrap_response(resp) end |
#request(method, path, body = nil, attempt = 1) ⇒ Object
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 |
# File 'lib/sale/base.rb', line 38 def request(method, path, body = nil, attempt = 1) headers = { 'access_token' => @token } url = path['://'] ? path : [ ENDPOINT, VERSION, path ].join('/') if @http @http.request(method, url, body, { json: true, follow: 3, headers: headers }) else Dagger.request(method, url, body, { json: true, follow: 3, headers: headers }) end rescue InvalidResponseError, Errno::ECONNREFUSED, Errno::ECONNRESET, Errno::ETIMEDOUT, Errno::EINVAL, Timeout::Error, \ SocketError, EOFError, Net::HTTPBadResponse, Net::HTTPHeaderSyntaxError, Net::ProtocolError, OpenSSL::SSL::SSLError => e raise if attempt > MAX_RETRIES puts "Connection refused. Retrying in a few secs... (attempt #{attempt})" sleep(attempt * 5) # 5 secs, 10 secs, 15 secs, 20 secs request(method, path, body, attempt + 1) end |