Skip to content

Commit

Permalink
Merge pull request #11 from eugenebolshakov/reuse_session
Browse files Browse the repository at this point in the history
Login once and re-use session (and re-login if it expires)
  • Loading branch information
pstuteville committed Sep 16, 2011
2 parents 6478981 + da860d7 commit 97db38b
Showing 1 changed file with 24 additions and 9 deletions.
33 changes: 24 additions & 9 deletions lib/magento/connection.rb
Original file line number Diff line number Diff line change
@@ -1,24 +1,39 @@
module Magento
class Connection
attr_accessor :client, :config, :logger
attr_accessor :session, :config, :logger

def initialize(config = {})
@logger ||= Logger.new(STDOUT)
@config = config
self
end


def client
@client ||= XMLRPC::Client.new(config[:host], config[:path], config[:port])
end

def connect
@client = XMLRPC::Client.new(config[:host], config[:path], config[:port])
@session = @client.call("login", config[:username], config[:api_key])
connect! if session.nil?
end

def call(method = nil, *args)
@logger.debug "call: #{method}, #{args.inspect}"
logger.debug "call: #{method}, #{args.inspect}"
connect
@client.call("call", @session, method, args)
client.call("call", session, method, args)
rescue XMLRPC::FaultException => e
@logger.debug "exception: #{e.faultCode} -> #{e.faultString}"
logger.debug "exception: #{e.faultCode} -> #{e.faultString}"
if e.faultCode == 5 # Session timeout
connect!
retry
end
raise Magento::ApiError, "#{e.faultCode} -> #{e.faultString}"
end

private

def connect!
logger.debug "call: login"
@session = client.call("login", config[:username], config[:api_key])
end
end
end
end

0 comments on commit 97db38b

Please sign in to comment.