Class: Pricefinder::Client

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

Constant Summary collapse

API_HOST =
'https://api.pricefinder.com.au/v1'
USER_AGENT =
"Pricefinder Ruby Wrapper #{Pricefinder::VERSION}"

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = nil) ⇒ Client

Returns a new instance of Client.



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

def initialize(options = nil)
  @config = nil
  @retry_count = 0

  unless options.nil?
    @configuration = Configuration.new(options)
    check_valid_config
  end

  # Create Connection
  connection

  # Get Access Token
  get_access_token
end

Instance Attribute Details

#configurationObject (readonly)

Returns the value of attribute configuration.



13
14
15
# File 'lib/pricefinder/client.rb', line 13

def configuration
  @configuration
end

Instance Method Details

#access_tokenObject



50
51
52
# File 'lib/pricefinder/client.rb', line 50

def access_token
  @configuration.access_token
end

#build_errors(response) ⇒ Object



69
70
71
72
73
74
75
# File 'lib/pricefinder/client.rb', line 69

def build_errors(response)
  errors = []
  errors << "Unauthorized Token: #{access_token}" if response.status == 401
  errors << "Could not handle response" if response.status == 500

  return errors
end

#check_valid_configObject



31
32
33
34
35
36
# File 'lib/pricefinder/client.rb', line 31

def check_valid_config
  if configuration.nil? || !configuration.valid?
    @configuration = nil
    raise Error::MissingClientRequiredConfig
  end
end

#connectionObject



38
39
40
41
42
43
44
45
46
47
48
# File 'lib/pricefinder/client.rb', line 38

def connection
  return @connection if instance_variable_defined?(:@connection)
  check_valid_config

  @connection = Faraday.new(API_HOST) do |faraday|
    faraday.request  :url_encoded
    faraday.headers[:user_agent] = USER_AGENT
    faraday.response :json
    faraday.adapter Faraday.default_adapter
  end
end

#get(path, params = {}, options = {}) ⇒ Object



54
55
56
57
58
59
60
61
62
# File 'lib/pricefinder/client.rb', line 54

def get(path, params = {}, options = {})
  response = @connection.get do |request|
    request.headers['Authorization'] = "Bearer #{access_token}"
    request.url path
    request.params = params
  end

  handle_response(response)
end

#handle_response(response) ⇒ Object



64
65
66
67
# File 'lib/pricefinder/client.rb', line 64

def handle_response(response)
  return response.body if response.body
  return { errors: build_errors(response) }
end

#handle_unauthorizedObject



77
78
79
80
81
82
83
84
85
# File 'lib/pricefinder/client.rb', line 77

def handle_unauthorized
  if @retry_count == 0
    # Get a new access token
    get_access_token(true)
    
    # Retry
    @retry_count += 1
  end
end