Class: Limiter::Client

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

Direct Known Subclasses

Points

Constant Summary collapse

BASE_URL =
"https://api.limiter.dev"

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

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

Returns a new instance of Client.



13
14
15
16
17
18
19
20
# File 'lib/limiter/client.rb', line 13

def initialize(namespace:, limit:, interval:)
  @namespace = namespace
  @limit = limit
  @interval = interval.to_i
  @logger = Limiter.logger

  ErrorHandler.error("API Token is not set") if Limiter.configuration.api_token.nil?
end

Instance Attribute Details

#identifierObject (readonly)

Returns the value of attribute identifier.



10
11
12
# File 'lib/limiter/client.rb', line 10

def identifier
  @identifier
end

#intervalObject (readonly)

Returns the value of attribute interval.



10
11
12
# File 'lib/limiter/client.rb', line 10

def interval
  @interval
end

#limitObject (readonly)

Returns the value of attribute limit.



10
11
12
# File 'lib/limiter/client.rb', line 10

def limit
  @limit
end

#namespaceObject (readonly)

Returns the value of attribute namespace.



10
11
12
# File 'lib/limiter/client.rb', line 10

def namespace
  @namespace
end

#responseObject (readonly)

Returns the value of attribute response.



10
11
12
# File 'lib/limiter/client.rb', line 10

def response
  @response
end

#tokenObject (readonly)

Returns the value of attribute token.



10
11
12
# File 'lib/limiter/client.rb', line 10

def token
  @token
end

Instance Method Details

#check(identifier) ⇒ Object



22
23
24
25
26
27
28
29
30
# File 'lib/limiter/client.rb', line 22

def check(identifier)
  @identifier = identifier
  @logger.info("check: #{namespace}/#{limit}/#{interval}/#{identifier}")
  @response = ResponseHandler.new(request)
  self
rescue => e
  ErrorHandler.error("check failed: #{e.message}")
  self
end

#formatted_intervalObject



32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/limiter/client.rb', line 32

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

#limiter_pathObject



47
48
49
# File 'lib/limiter/client.rb', line 47

def limiter_path
  "/ctr/#{namespace}/#{limit}/#{formatted_interval}/#{identifier}"
end

#request(params = {}) ⇒ Object



51
52
53
54
55
56
# File 'lib/limiter/client.rb', line 51

def request(params = {})
  ::HTTP
    .auth("Bearer #{Limiter.configuration.api_token}")
    .headers("User-Agent" => "Limiter-Ruby/#{Limiter::VERSION}")
    .get(BASE_URL + limiter_path, params: params)
end