lib/ably/rest/client.rb in ably-0.1.0 vs lib/ably/rest/client.rb in ably-0.1.1

- old
+ new

@@ -22,11 +22,11 @@ include Ably::Support extend Forwardable DOMAIN = "rest.ably.io" - attr_reader :tls, :environment, :auth + attr_reader :tls, :environment, :auth, :channels def_delegator :auth, :client_id, :auth_options # Creates a {Ably::Rest::Client Rest Client} and configures the {Ably::Auth} object for the connection. # # @param [Hash,String] options an options Hash used to configure the client and the authentication, or String with an API key @@ -59,28 +59,30 @@ # # # create a new client and configure a client ID used for presence # client = Ably::Rest::Client.new(api_key: 'key.id:secret', client_id: 'john') # def initialize(options, &auth_block) + options = options.dup + if options.kind_of?(String) options = { api_key: options } end @tls = options.delete(:tls) == false ? false : true @environment = options.delete(:environment) # nil is production @debug_http = options.delete(:debug_http) - @auth = Auth.new(self, options, &auth_block) + @auth = Auth.new(self, options, &auth_block) + @channels = Ably::Rest::Channels.new(self) end # Return a REST {Ably::Rest::Channel} for the given name # - # @param name [String] The name of the channel - # @return [Ably::Rest::Channel] - def channel(name) - @channels ||= {} - @channels[name] ||= Ably::Rest::Channel.new(self, name) + # @param [String] name see {Ably::Rest::Channels#get} + # @param [Hash] channel_options see {Ably::Rest::Channels#get} + def channel(name, channel_options = {}) + channels.get(name, channel_options) end # Return the stats for the application # # @return [Array] An Array of hashes representing the stats @@ -135,12 +137,29 @@ ) end private def request(method, path, params = {}, options = {}) - connection.send(method, path, params) do |request| - unless options[:send_auth_header] == false - request.headers[:authorization] = auth.auth_header + reauthorise_on_authorisation_failure do + connection.send(method, path, params) do |request| + unless options[:send_auth_header] == false + request.headers[:authorization] = auth.auth_header + end + end + end + end + + def reauthorise_on_authorisation_failure + attempts = 0 + begin + yield + rescue Ably::Exceptions::InvalidRequest => e + attempts += 1 + if attempts == 1 && e.code == 40140 && auth.token_renewable? + auth.authorise force: true + retry + else + raise Ably::Exceptions::InvalidToken.new(e.message, status: e.status, code: e.code) end end end # Return a Faraday::Connection to use to make HTTP requests