Class: Limiter::Client

Inherits:
Object
  • Object
show all
Defined in:
lib/limiter/client.rb

Direct Known Subclasses

Points

Constant Summary collapse

BASE_DOMAIN =
"https://api.limiter.dev".freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(namespace:, limit:, period:) ⇒ Client

Returns a new instance of Client.



10
11
12
13
14
15
16
17
# File 'lib/limiter/client.rb', line 10

def initialize(namespace:, limit:, period:)
  @namespace = namespace
  @limit = limit
  @period = period.to_i
  @token = ENV["LIMITER_TOKEN"]

  ErrorHandler.error("LIMITER_TOKEN environment variable is not set") if @token.nil?
end

Instance Attribute Details

#identifierObject (readonly)

Returns the value of attribute identifier.



8
9
10
# File 'lib/limiter/client.rb', line 8

def identifier
  @identifier
end

#limitObject (readonly)

Returns the value of attribute limit.



8
9
10
# File 'lib/limiter/client.rb', line 8

def limit
  @limit
end

#namespaceObject (readonly)

Returns the value of attribute namespace.



8
9
10
# File 'lib/limiter/client.rb', line 8

def namespace
  @namespace
end

#periodObject (readonly)

Returns the value of attribute period.



8
9
10
# File 'lib/limiter/client.rb', line 8

def period
  @period
end

#tokenObject (readonly)

Returns the value of attribute token.



8
9
10
# File 'lib/limiter/client.rb', line 8

def token
  @token
end

Instance Method Details

#check(identifier) ⇒ Object



19
20
21
22
# File 'lib/limiter/client.rb', line 19

def check(identifier)
  @identifier = identifier
  RateLimitResponse.new(request)
end

#formatted_periodObject



24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/limiter/client.rb', line 24

def formatted_period
  case @period
  when 1..59
    (@period).to_s + "s"
  when 60..3599
    (@period / 60).to_s + "m"
  when 3600..86_399
    (@period / 3600).to_s + "h"
  when 86_400..1_209_599
    (@period / 86_400).to_s + "d"
  else
    ErrorHandler.error("Invalid period")
  end
end

#request(params = {}) ⇒ Object



43
44
45
# File 'lib/limiter/client.rb', line 43

def request(params = {})
  HTTP.get(url, params: { token: token}.merge(params))
end

#urlObject



39
40
41
# File 'lib/limiter/client.rb', line 39

def url
  "#{BASE_DOMAIN}/ns/#{namespace}/#{limit}/#{formatted_period}/#{identifier}"
end