Class: AthenaHealth::Connection

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

Constant Summary collapse

PRODUCTION_BASE_URL =
'https://api.platform.athenahealth.com'.freeze
PREVIEW_BASE_URL =
'https://api.preview.platform.athenahealth.com'.freeze
API_VERSION =
'v1'.freeze

Instance Method Summary collapse

Constructor Details

#initialize(client_id:, secret:, token: nil, production:) ⇒ Connection

Returns a new instance of Connection.



9
10
11
12
13
14
# File 'lib/athena_health/connection.rb', line 9

def initialize(client_id:, secret:, token: nil, production: )
  @client_id = client_id
  @secret = secret
  @token = token
  @production = production
end

Instance Method Details

#authenticateObject



16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/athena_health/connection.rb', line 16

def authenticate
  response = Typhoeus.post(
    "#{base_url}/oauth2/#{API_VERSION}/token",
    userpwd: "#{@client_id}:#{@secret}",
    body: { 
      grant_type: 'client_credentials', 
      scope: 'athena/service/Athenanet.MDP.*' 
    }
  ).response_body

  @token = JSON.parse(response)['access_token']
end

#call(endpoint:, method:, params: {}, body: {}, second_call: false) ⇒ Object



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/athena_health/connection.rb', line 29

def call(endpoint:, method:, params: {}, body: {}, second_call: false)
  authenticate if @token.nil?

  response = Typhoeus::Request.new(
    "#{base_url}/#{API_VERSION}/#{endpoint}",
    method: method,
    headers: { "Authorization" => "Bearer #{@token}"},
    params: params,
    body: body
  ).run

  if response.response_code == 401 && !second_call
    authenticate
    return call(endpoint: endpoint, method: method, second_call: true, body: body, params: params)
  end

  if response.response_code == 403 && !second_call
    return call(endpoint: endpoint, method: method, second_call: true, body: body, params: params)
  end

  body = response.response_body

  if [400, 409].include? response.response_code
    fail AthenaHealth::ValidationError.new(json_response(body))
  end

  if response.response_code != 200
    AthenaHealth::Error.new(code: response.response_code).render
  end

  json_response(body)
end