diff --git a/lib/github/client.rb b/lib/github/client.rb index 95536cae57f..bf1b2b0a523 100644 --- a/lib/github/client.rb +++ b/lib/github/client.rb @@ -1,17 +1,19 @@ module Github class Client - attr_reader :connection + attr_reader :connection, :rate_limit def initialize(options) @connection = Faraday.new(url: options.fetch(:url)) do |faraday| faraday.authorization 'token', options.fetch(:token) faraday.adapter :net_http end + + @rate_limit = RateLimit.new(connection) end def get(url, query = {}) - rate_limit = RateLimit.new(connection) - sleep rate_limit.reset_in if rate_limit.exceed? + exceed, reset_in = rate_limit.get + sleep reset_in if exceed Github::Response.new(connection.get(url, query)) end diff --git a/lib/github/rate_limit.rb b/lib/github/rate_limit.rb index ab2b9c707d8..884693d093c 100644 --- a/lib/github/rate_limit.rb +++ b/lib/github/rate_limit.rb @@ -10,33 +10,18 @@ module Github @connection = connection end - def exceed? - return false unless enabled? + def get + response = connection.get(RATE_LIMIT_URL) - remaining <= SAFE_REMAINING_REQUESTS - end + # GitHub Rate Limit API returns 404 when the rate limit is disabled + return false unless response.status != 404 - def remaining - @remaining ||= body.dig('rate', 'remaining').to_i - end + body = Oj.load(response.body, class_cache: false, mode: :compat) + remaining = body.dig('rate', 'remaining').to_i + reset_in = body.dig('rate', 'reset').to_i + exceed = remaining <= SAFE_REMAINING_REQUESTS - def reset_in - @reset ||= body.dig('rate', 'reset').to_i - end - - private - - def response - connection.get(RATE_LIMIT_URL) - end - - def body - @body ||= Oj.load(response.body, class_cache: false, mode: :compat) - end - - # GitHub Rate Limit API returns 404 when the rate limit is disabled - def enabled? - response.status != 404 + [exceed, reset_in] end end end