lib/lol/request.rb in ruby-lol-1.0.0 vs lib/lol/request.rb in ruby-lol-1.1.1

- old
+ new

@@ -22,10 +22,14 @@ # @!attribute[r] cache_store # @return [Object] the cache_store attr_reader :cache_store + # @!attribute[r] rate_limiter + # @return [Object] the rate limiter, if one exists (else nil) + attr_reader :rate_limiter + # Returns the supported API Version. # @return [String] v3 def self.api_version "v3" end @@ -52,19 +56,20 @@ # @param cache_store [Hash] # @option cache_store [Redis] :redis Redis instance to use # @option cache_store [Boolean] :cached should the request be cached # @option cacche_store [Integer] :ttl ttl for cache keys # @return [Request] - def initialize api_key, region, cache_store = {} - @cache_store = cache_store + def initialize api_key, region, cache_store = {}, rate_limiter = nil + @cache_store = cache_store + @rate_limiter = rate_limiter raise InvalidCacheStore if cached? && !store.is_a?(Redis) @api_key = api_key - @region = region + @region = region end def platform - self.class.platforms[region.to_sym] + self.class.platforms[region.downcase.to_sym] end # Returns the supported API Version. # @return [String] v3 def api_version @@ -101,11 +106,12 @@ uri = URI.parse(url) uri.query = CGI.parse(uri.query || '').reject { |k| k == 'api_key' }.to_query uri.to_s end - # Calls the API via HTTParty and handles errors + # Calls the API via HTTParty and handles errors caching it if a cache is + # enabled and rate limiting it if a rate limiter is configured # @param url [String] the url to call # @param verb [Symbol] HTTP verb to use. Defaults to :get # @param body [Hash] Body for POST request # @param options [Hash] Options passed to HTTParty # @return [String] raw response of the call @@ -113,12 +119,19 @@ options_id = options.inspect can_cache = [:post, :put].include?(verb) ? false : cached? if can_cache && result = store.get("#{clean_url(url)}#{options_id}") return JSON.parse(result) end - response = perform_uncached_request url, verb, body, options + response = perform_rate_limited_request(url, verb, body, options) store.setex "#{clean_url(url)}#{options_id}", ttl, response.to_json if can_cache response + end + + def perform_rate_limited_request url, verb = :get, body = nil, options = {} + return perform_uncached_request(url, verb, body, options) unless rate_limiter + @rate_limiter.times 1 do + perform_uncached_request(url, verb, body, options) + end end def perform_uncached_request url, verb = :get, body = nil, options = {} options[:headers] ||= {} options[:headers].merge!({