Sha256: 9473c0912c2979fa804285aaf7d2e5c5f531d0b28bffe4cecd9449ff11ffdc7e

Contents?: true

Size: 1.51 KB

Versions: 5

Compression:

Stored size: 1.51 KB

Contents

require 'json'

module AthenaHealth
  class Connection
    BASE_URL    = 'https://api.athenahealth.com'.freeze
    AUTH_PATH   = { 'v1' => 'oauth', 'preview1' => 'oauthpreview', 'openpreview1' => 'oauthopenpreview' }

    def initialize(version:, key:, secret:)
      @version = version
      @key = key
      @secret = secret
    end

    def authenticate
      response = Typhoeus.post(
        "#{BASE_URL}/#{AUTH_PATH[@version]}/token",
        userpwd: "#{@key}:#{@secret}",
        body: { grant_type: 'client_credentials' }
      ).response_body

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

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

      response = Typhoeus::Request.new(
        "#{BASE_URL}/#{@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

      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

    private

    def json_response(body)
      JSON.parse(body)
    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
athena_health-1.0.10 lib/athena_health/connection.rb
athena_health-1.0.9 lib/athena_health/connection.rb
athena_health-1.0.8 lib/athena_health/connection.rb
athena_health-1.0.7 lib/athena_health/connection.rb
athena_health-1.0.6 lib/athena_health/connection.rb