lib/parcel_api/client.rb in parcel_api-0.4.1 vs lib/parcel_api/client.rb in parcel_api-1.0.0
- old
+ new
@@ -1,14 +1,21 @@
+require 'oauth2'
+require 'redis'
+
+require 'active_support'
+require 'active_support/core_ext/numeric/time'
+
module ParcelApi
class Client
attr_accessor :client_id,
:client_secret,
:username,
:password,
:address,
- :auth_address
+ :auth_address,
+ :redis
def self.connection
@connection ||= new.connection
end
@@ -17,41 +24,28 @@
@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
def connection
- Faraday.new(url: @address) do |conn|
- conn.authorization 'Bearer', token
- conn.headers['client_id'] = @client_id
- conn.request :json
- conn.response :json, :content_type => /\bjson$/
- conn.use FaradayMiddleware::RaiseHttpException
- conn.adapter Faraday.default_adapter
+ @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
private
- def token
- params = {
- client_id: @client_id,
- client_secret: @client_secret,
- username: @username,
- password: @password,
- grant_type: 'password',
- }
-
- auth_api = Faraday.new do |conn|
- conn.request :url_encoded
- conn.response :json
- conn.use FaradayMiddleware::RaiseHttpException
- conn.adapter Faraday.default_adapter
- end
- response = auth_api.post @auth_address, params
- response.body['access_token']
+ def client
+ OAuth2::Client.new(@client_id, @client_secret, site: @address, token_url: @auth_address, connection_opts: { headers: { 'client_id' => @client_id } })
end
end
end