Class: Youlend::Connection

Inherits:
Object
  • Object
show all
Defined in:
lib/youlend/connection.rb

Constant Summary collapse

BASE_PATH =
'/'

Instance Method Summary collapse

Instance Method Details

#get(path, audience) ⇒ Object



58
59
60
61
62
63
64
# File 'lib/youlend/connection.rb', line 58

def get(path, audience)
  http_response = with_token_refresh(audience) do
    adapter(audience).get(PathSanitizer.sanitize(path))
  end

  Response.new(http_response)
end

#post(path, audience, params = {}) ⇒ Object



38
39
40
41
42
43
44
45
46
# File 'lib/youlend/connection.rb', line 38

def post(path, audience, params = {})
  log "POST: #{params.inspect}"

  http_response = with_token_refresh(audience) do
    adapter(audience).post(PathSanitizer.sanitize(path), params.to_json)
  end

  Response.new(http_response)
end

#put(path, audience, params = {}) ⇒ Object



48
49
50
51
52
53
54
55
56
# File 'lib/youlend/connection.rb', line 48

def put(path, audience, params = {})
  log "PUT: #{params.inspect}"

  http_response = with_token_refresh(audience) do
    adapter(audience).put(PathSanitizer.sanitize(path), params.to_json)
  end

  Response.new(http_response)
end

#with_token_refresh(audience) ⇒ Object



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/youlend/connection.rb', line 14

def with_token_refresh(audience)
  if token_for(audience).to_s.empty?
    log "Refreshing outdated token... #{Youlend.configuration.tokens[audience]}"

    Auth.request_token(audience)
  end

  http_response = yield

  response = Response.new(http_response)

  # Try to get a valid token if the token has expired. This will also update the gem config
  # so we won't need to request the token again.
  if response.token_expired? || response.unauthorized?
    log "Refreshing outdated token... #{Youlend.configuration.tokens[audience]}"

    Auth.request_token(audience)

    http_response = yield
  end

  http_response
end