Class: ParcelApi::Client

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

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeClient

Returns a new instance of Client.



22
23
24
25
26
27
28
29
30
# File 'lib/parcel_api/client.rb', line 22

def initialize
  @client_id     = client_id     || ENV['CLIENT_ID']
  @client_secret = client_secret || ENV['CLIENT_SECRET']
  @username      = username      || ENV['USERNAME']
  @password      = password      || ENV['PASSWORD']
  @address       = address       || 'https://api.nzpost.co.nz'
  @auth_address  = auth_address  || 'https://oauth.nzpost.co.nz/as/token.oauth2'
  @redis         = redis         || Redis.new
end

Instance Attribute Details

#address

Returns the value of attribute address.



10
11
12
# File 'lib/parcel_api/client.rb', line 10

def address
  @address
end

#auth_address

Returns the value of attribute auth_address.



10
11
12
# File 'lib/parcel_api/client.rb', line 10

def auth_address
  @auth_address
end

#client_id

Returns the value of attribute client_id.



10
11
12
# File 'lib/parcel_api/client.rb', line 10

def client_id
  @client_id
end

#client_secret

Returns the value of attribute client_secret.



10
11
12
# File 'lib/parcel_api/client.rb', line 10

def client_secret
  @client_secret
end

#password

Returns the value of attribute password.



10
11
12
# File 'lib/parcel_api/client.rb', line 10

def password
  @password
end

#redis

Returns the value of attribute redis.



10
11
12
# File 'lib/parcel_api/client.rb', line 10

def redis
  @redis
end

#username

Returns the value of attribute username.



10
11
12
# File 'lib/parcel_api/client.rb', line 10

def username
  @username
end

Class Method Details

.connection



18
19
20
# File 'lib/parcel_api/client.rb', line 18

def self.connection
  @connection ||= new.connection
end

Instance Method Details

#connection



32
33
34
35
36
37
38
39
40
41
42
# File 'lib/parcel_api/client.rb', line 32

def connection
  @access_token_cache ||= begin
    if json = @redis.get(:parcel_api_access_token)
      access_token = OAuth2::AccessToken.from_hash client, JSON.parse(json)
    else
      access_token = client.password.get_token @username, @password
      @redis.set(:parcel_api_access_token, access_token.to_hash.to_json, ex: access_token.expires_in.seconds - 1.minute)
      access_token
    end
  end
end