Class: Bsale::APIBase

Inherits:
Object
  • Object
show all
Defined in:
lib/sale/base.rb

Direct Known Subclasses

Root

Constant Summary collapse

ENDPOINT =
'https://api.bsale.cl'.freeze
VERSION =
'v1'.freeze
MAX_RETRIES =
5

Instance Method Summary collapse

Constructor Details

#initialize(token) ⇒ APIBase

Returns a new instance of APIBase.



15
16
17
# File 'lib/sale/base.rb', line 15

def initialize(token)
  @token = token or raise 'Token not set!'
end

Instance Method Details

#connect(opts = {}) ⇒ Object



63
64
65
# File 'lib/sale/base.rb', line 63

def connect(opts = {})
  @http ||= Dagger.open(ENDPOINT, opts)
end

#delete(path) ⇒ Object



35
36
37
38
# File 'lib/sale/base.rb', line 35

def delete(path)
  resp = request(:delete, path)
  wrap_response(resp)
end

#disconnectObject



67
68
69
70
# File 'lib/sale/base.rb', line 67

def disconnect
  @http.close if @http
  @http = nil
end

#get(path, params = nil) ⇒ Object



19
20
21
22
23
# File 'lib/sale/base.rb', line 19

def get(path, params = nil)
  path = params.nil? ? path : path + "?" + Dagger::Utils.to_query_string(params)
  resp = request(:get, path)
  wrap_response(resp, params)
end

#post(path, data) ⇒ Object



25
26
27
28
# File 'lib/sale/base.rb', line 25

def post(path, data)
  resp = request(:post, path, data)
  wrap_response(resp)
end

#put(path, data) ⇒ Object



30
31
32
33
# File 'lib/sale/base.rb', line 30

def put(path, data)
  resp = request(:put, path, data)
  wrap_response(resp)
end

#request(method, path, body = nil, attempt = 1) ⇒ Object



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/sale/base.rb', line 40

def request(method, path, body = nil, attempt = 1)
  headers = { 'access_token' => @token }
  url = path['://'] ? path : [ ENDPOINT, VERSION, path ].join('/')

  resp = if @http
    @http.request(method, url, body, { json: true, follow: 3, retries: 3, headers: headers })
  else
    Dagger.request(method, url, body, { json: true, follow: 3, retries: 3, headers: headers })
  end

  if resp.code > 500
    raise ServerError.new("#{resp.code}: #{resp.body}")
  else
    resp
  end

rescue ServerError => e
  raise if attempt > MAX_RETRIES
  puts "#{e.class}. Retrying in a few secs... (attempt #{attempt})"
  sleep(attempt * 3) # 3 secs, 6 secs, 9 secs, 12 secs
  request(method, path, body, attempt + 1)
end