# frozen_string_literal: true require "net/http" class NeetoCommonsBackend::Helpers::AuthServerApi MAX_RETRIES = 5 REQUEST_CLASSES = { get: Net::HTTP::Get, post: Net::HTTP::Post, put: Net::HTTP::Put, delete: Net::HTTP::Delete } attr_reader :endpoint, :request_body, :request_class, :request_params, :custom_headers def initialize(custom_headers: {}) @custom_headers = custom_headers end def get(**args) request(type: :get, **args) end def put(**args) request(type: :put, **args) end def post(**args) request(type: :post, **args) end def delete(**args) request(type: :delete, **args) end def request(type:, **args) return if Rails.env.heroku? @request_class = REQUEST_CLASSES[type] process(**args) end private def process(endpoint:, params: nil, body: nil) @endpoint = endpoint @request_params = params @request_body = body begin retry_count ||= 0 send_request rescue StandardError => exception if retry_count < MAX_RETRIES retry_count += 1 Rails.logger.warn "Error: #{exception.message}. Retrying in #{2**retry_count} seconds." sleep 2**retry_count retry else Rails.logger.error "Retries exhausted" raise exception end end end def send_request http = Net::HTTP.new(uri.host, uri.port) http.use_ssl = true if uri.scheme == "https" request = request_class.new(uri.request_uri, headers) if request_body.present? request.body = request_body.to_json end response = http.request(request) response.body end def uri return @uri if @uri.present? @uri = URI.parse("#{Rails.application.secrets.auth_app[:url]}/api/v1/server/#{endpoint}") if request_params.present? @uri.query = URI.encode_www_form(request_params) end @uri end def headers { "Content-Type" => "application/json", "AUTHORIZATION" => "Token token=#{Rails.application.secrets.server_authorization_token}" }.merge(custom_headers) end end