Class: Redox::Source

Inherits:
Object
  • Object
show all
Includes:
MonitorMixin
Defined in:
lib/redox/source.rb

Constant Summary collapse

SECONDS_PER_DAY =
60 * 60 * 24
ACCESS_TOKEN_EXPIRATION_BUFFER =
Rational(300, SECONDS_PER_DAY)

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(endpoint:, api_key:, secret:, test_mode: true) ⇒ Source

Returns a new instance of Source.



15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/redox/source.rb', line 15

def initialize(endpoint:, api_key:, secret:, test_mode: true)
  super()
  @connection = Faraday.new(
    url: endpoint,
    headers: {
      accept: "application/json",
      content_type: "application/json"
    }
  )
  @endpoint = endpoint
  @api_key = api_key
  @secret = secret
  @test_mode = test_mode
end

Instance Attribute Details

#access_token_expires_atObject (readonly)

Returns the value of attribute access_token_expires_at.



13
14
15
# File 'lib/redox/source.rb', line 13

def access_token_expires_at
  @access_token_expires_at
end

#api_keyObject (readonly)

Returns the value of attribute api_key.



13
14
15
# File 'lib/redox/source.rb', line 13

def api_key
  @api_key
end

#endpointObject (readonly)

Returns the value of attribute endpoint.



13
14
15
# File 'lib/redox/source.rb', line 13

def endpoint
  @endpoint
end

Instance Method Details

#access_tokenObject



56
57
58
# File 'lib/redox/source.rb', line 56

def access_token
  @connection.headers["Authorization"]&.delete_prefix "Bearer "
end

#access_token=(token) ⇒ Object



60
61
62
63
64
65
66
# File 'lib/redox/source.rb', line 60

def access_token=(token)
  if token.nil?
    @connection.headers.delete "Authorization"
  else
    @connection.authorization :Bearer, token
  end
end

#ensure_access_tokenObject



50
51
52
53
54
# File 'lib/redox/source.rb', line 50

def ensure_access_token
  synchronize {
    authenticate if access_token.nil? || token_expiring_soon?
  }
end

#execute_query(model) ⇒ Object



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/redox/source.rb', line 30

def execute_query(model)
  ensure_access_token
  res = @connection.post("/endpoint", model.to_redox_json)
  message =
    begin
      JSON.parse(res.body)
    rescue
      nil
    end

  unless res.success?
    raise Redox::Error.new(
      status: res.status,
      body: res.body,
      message: Redox::Models::Message.from_redox_json(message)
    )
  end
  message
end

#token_expiring_soon?Boolean

Returns:

  • (Boolean)


68
69
70
# File 'lib/redox/source.rb', line 68

def token_expiring_soon?
  DateTime.now > @access_token_expires_at - ACCESS_TOKEN_EXPIRATION_BUFFER
end