Refactoring Github::RateLimit

parent f73a0280
module Github module Github
class Client class Client
attr_reader :connection attr_reader :connection, :rate_limit
def initialize(options) def initialize(options)
@connection = Faraday.new(url: options.fetch(:url)) do |faraday| @connection = Faraday.new(url: options.fetch(:url)) do |faraday|
faraday.authorization 'token', options.fetch(:token) faraday.authorization 'token', options.fetch(:token)
faraday.adapter :net_http faraday.adapter :net_http
end end
@rate_limit = RateLimit.new(connection)
end end
def get(url, query = {}) def get(url, query = {})
rate_limit = RateLimit.new(connection) exceed, reset_in = rate_limit.get
sleep rate_limit.reset_in if rate_limit.exceed? sleep reset_in if exceed
Github::Response.new(connection.get(url, query)) Github::Response.new(connection.get(url, query))
end end
......
...@@ -10,33 +10,18 @@ module Github ...@@ -10,33 +10,18 @@ module Github
@connection = connection @connection = connection
end end
def exceed? def get
return false unless enabled? response = connection.get(RATE_LIMIT_URL)
remaining <= SAFE_REMAINING_REQUESTS # GitHub Rate Limit API returns 404 when the rate limit is disabled
end return false unless response.status != 404
def remaining
@remaining ||= body.dig('rate', 'remaining').to_i
end
def reset_in
@reset ||= body.dig('rate', 'reset').to_i
end
private body = Oj.load(response.body, class_cache: false, mode: :compat)
remaining = body.dig('rate', 'remaining').to_i
def response reset_in = body.dig('rate', 'reset').to_i
connection.get(RATE_LIMIT_URL) exceed = remaining <= SAFE_REMAINING_REQUESTS
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 [exceed, reset_in]
def enabled?
response.status != 404
end end
end end
end end
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment