Class: SacsRuby::Client

Inherits:
Object
  • Object
show all
Defined in:
lib/sacs_ruby/client.rb

Overview

Client class

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeClient

Returns a new instance of Client.



6
7
8
# File 'lib/sacs_ruby/client.rb', line 6

def initialize
  @credentials = Credentials.new
end

Instance Attribute Details

#access_tokenObject

Returns the value of attribute access_token.



4
5
6
# File 'lib/sacs_ruby/client.rb', line 4

def access_token
  @access_token
end

#expires_onObject

Returns the value of attribute expires_on.



4
5
6
# File 'lib/sacs_ruby/client.rb', line 4

def expires_on
  @expires_on
end

Instance Method Details

#fetch_tokenObject



70
71
72
73
74
75
76
77
# File 'lib/sacs_ruby/client.rb', line 70

def fetch_token
  response = request_token(@credentials.encoded)
  parsed_response = JSON.load(response)

  self.access_token = parsed_response['access_token']
  self.expires_on = Time.now.utc + parsed_response['expires_in'].to_i
  self
end

#get(params) ⇒ Object



10
11
12
13
14
15
16
17
18
19
# File 'lib/sacs_ruby/client.rb', line 10

def get(params)
  token = params.fetch(:token, nil) || access_token
  RestClient::Request.execute(
    method: :get,
    url: params[:url],
    headers: { 'Authorization' => "Bearer #{token}" }
  ) do |response, request, result, &block|
    case_response(response, request, result, 'get', &block)
  end
end

#post(params) ⇒ Object

rubocop:disable MethodLength



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/sacs_ruby/client.rb', line 21

def post(params) # rubocop:disable MethodLength
  token = params.fetch(:token, nil) || access_token
  RestClient::Request.execute(
    method: :post,
    url: params[:url],
    payload: params[:payload],
    headers: {
      'Authorization' => "Bearer #{token}",
      'Content-Type' => 'application/json',
      'Accept-Encoding' => 'gzip'
    }
  ) do |response, request, result, &block|
    case_response(response, request, result, 'post', &block)
  end
end

#request_token(auth_key) ⇒ Object

rubocop:disable MethodLength



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/sacs_ruby/client.rb', line 37

def request_token(auth_key) # rubocop:disable MethodLength
  RestClient::Request.execute(
    method: :post,
    url: SacsRuby.configuration.auth_base_url,
    payload: 'grant_type=client_credentials',
    headers: {
      'Authorization' => "Basic #{auth_key}",
      'Content-Type' => 'application/x-www-form-urlencoded'
    }) do |response, request, result, &block|
      case response.code
      when 200
        response
      when 401
        parsed_response = JSON.load(response)
        fail TokenRequestError, parsed_response
      when 429
        parsed_response = JSON.load(response)
        fail TooManyRequestsError, parsed_response
      else
        response.return!(request, result, &block)
      end
    end
end