Class: ErpIntegration::Middleware::ApiKeysRotation

Inherits:
Faraday::Middleware
  • Object
show all
Defined in:
lib/erp_integration/middleware/api_keys_rotation.rb

Constant Summary collapse

HTTP_ROTATE_CODES =
[404, 429].freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(app, options = {}) ⇒ ApiKeysRotation

Returns a new instance of ApiKeysRotation.



10
11
12
13
14
# File 'lib/erp_integration/middleware/api_keys_rotation.rb', line 10

def initialize(app, options = {})
  super(app)

  @options = options
end

Instance Attribute Details

#optionsObject (readonly)

Returns the value of attribute options.



8
9
10
# File 'lib/erp_integration/middleware/api_keys_rotation.rb', line 8

def options
  @options
end

Instance Method Details

#call(env) ⇒ Object



16
17
18
19
20
# File 'lib/erp_integration/middleware/api_keys_rotation.rb', line 16

def call(env)
  on_request(env)

  @app.call(env).on_complete { |response| on_complete(response) }
end

#on_complete(env) ⇒ Object



26
27
28
29
30
# File 'lib/erp_integration/middleware/api_keys_rotation.rb', line 26

def on_complete(env)
  return unless rotate?(env)

  options[:api_keys_pool].rotate_key!
end

#on_request(env) ⇒ Object



22
23
24
# File 'lib/erp_integration/middleware/api_keys_rotation.rb', line 22

def on_request(env)
  env.request_headers['X-API-KEY'] = options[:api_keys_pool].current_key
end

#rotate?(env) ⇒ Boolean

Returns:

  • (Boolean)


32
33
34
35
36
37
# File 'lib/erp_integration/middleware/api_keys_rotation.rb', line 32

def rotate?(env)
  return true if HTTP_ROTATE_CODES.include?(env.status)
  return false unless env.response_headers['x-ratelimit-remaining'].present?

  env.response_headers['x-ratelimit-remaining'].to_i < options[:rotation_theshold].to_i
end