summaryrefslogtreecommitdiff
path: root/lib/github/rate_limit.rb
blob: 38beb6171737b67eb6d32376604b105c94c541a8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
module Github
  class RateLimit
    SAFE_REMAINING_REQUESTS = 100
    SAFE_RESET_TIME         = 500

    attr_reader :connection

    def initialize(connection)
      @connection = connection
    end

    def exceed?
      return false unless enabled?

      remaining <= SAFE_REMAINING_REQUESTS
    end

    def remaining
      @remaining ||= body.dig('rate', 'remaining').to_i
    end

    def reset_in
      @reset ||= body.dig('rate', 'reset').to_i
    end

    private

    def rate_limit_url
      '/rate_limit'
    end

    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
    end
  end
end