Class: Kontrast::ApiClient

Inherits:
Object
  • Object
show all
Defined in:
lib/kontrast/api_client.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(env, host, app_id, app_secret, headers: {}) ⇒ ApiClient

Returns a new instance of ApiClient.



9
10
11
12
13
14
15
16
17
# File 'lib/kontrast/api_client.rb', line 9

def initialize(env, host, app_id, app_secret, headers: {})
    @env = env
    @host = host
    @app_id = app_id
    @app_secret = app_secret
    @connection = nil
    @responses = {}
    @headers = headers
end

Instance Attribute Details

#envObject (readonly)

Returns the value of attribute env.



6
7
8
# File 'lib/kontrast/api_client.rb', line 6

def env
  @env
end

#headers=(value) ⇒ Object (writeonly)

Sets the attribute headers

Parameters:

  • value

    the value to set the attribute headers to.



7
8
9
# File 'lib/kontrast/api_client.rb', line 7

def headers=(value)
  @headers = value
end

#responsesObject (readonly)

Returns the value of attribute responses.



6
7
8
# File 'lib/kontrast/api_client.rb', line 6

def responses
  @responses
end

Instance Method Details

#connectionObject



49
50
51
52
53
54
# File 'lib/kontrast/api_client.rb', line 49

def connection
    @connection ||= Faraday.new(url: @host) do |faraday|
        faraday.request :url_encoded
        faraday.adapter Faraday.default_adapter
    end
end

#fetch(path, save_file: false, folder_name: "") ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/kontrast/api_client.rb', line 19

def fetch(path, save_file: false, folder_name: "")
    response = connection.get(path) do |req|
        req.headers['Authorization'] = "Bearer #{token}"
        req.headers.merge!(@headers)
    end
    data = JSON.parse(response.body)
    if save_file
        open(File.join(Kontrast.path, folder_name, "#{@env}.json"), 'wb') do |file|
            file << JSON.pretty_generate(data)
        end
    end
    @responses[path] = data
    return data
end

#fetch_tokenObject



38
39
40
41
42
43
44
45
46
47
# File 'lib/kontrast/api_client.rb', line 38

def fetch_token
    return @token if !@token.nil? && @token != ''

    response = connection.post(Kontrast.configuration.oauth_token_url, {
        grant_type: 'client_credentials',
        client_id: @app_id,
        client_secret: @app_secret,
    })
    @token = Kontrast.configuration.oauth_token_from_response.call(response.body)
end

#tokenObject



34
35
36
# File 'lib/kontrast/api_client.rb', line 34

def token
    return @token || fetch_token
end