# frozen_string_literal: true module ErpIntegration module Middleware class ApiKeysRotation < Faraday::Middleware HTTP_ROTATE_CODES = [404, 429].freeze attr_reader :options def initialize(app, options = {}) super(app) @options = options end def call(env) on_request(env) @app.call(env).on_complete { |response| on_complete(response) } end def on_request(env) env[:request_headers]['X-API-KEY'] = options[:api_keys_pool].current_key end def on_complete(env) return unless HTTP_ROTATE_CODES.include?(env.status) options[:api_keys_pool].rotate_key! end end end end