Sha256: afe06a7f33f08bf48c24f4cd3b0d82d0ccf231d93289b564cfa0e915277f437a

Contents?: true

Size: 1.96 KB

Versions: 1

Compression:

Stored size: 1.96 KB

Contents

# frozen_string_literal: true

require 'httparty'

module NoradBeacon
  # Class to post http payloads
  class NoradAPI
    include HTTParty
    @norad_root = ENV.fetch('NORAD_ROOT')
    MAX_ATTEMPTS = 10
    RETRY_BACKOFF = 2

    class << self
      def post_payload(http_payload)
        http_req http_payload, :post
      end

      def patch_payload(http_payload)
        http_req http_payload, :patch
      end

      def delete_payload(http_payload)
        http_req http_payload, :delete
      end

      alias post_results post_payload

      private

      def http_req_with_retry(verb, uri, payload)
        retries ||= 0
        send(verb, uri, payload)
      rescue SystemCallError, EOFError, Timeout::Error, SocketError
        sleep(RETRY_BACKOFF**retries) && retry if (retries += 1) < MAX_ATTEMPTS
        raise
      end

      def http_req(http_payload, verb)
        httpparty_response = http_req_with_retry(
          verb,
          @norad_root + http_payload.url,
          http_req_options(http_payload)
        )
        error_msg = unsuccessful_http_response_msg(httpparty_response)
        puts error_msg if error_msg
        httpparty_response
      end

      def unsuccessful_http_response_msg(httpparty_response)
        code = httpparty_response.response.code
        msg = httpparty_response.response.message
        heading = '[Beacon] Non-200 response received from API:'

        return nil unless display_http_error?(code, msg)
        return "#{heading} #{code}" if msg.nil? && code
        return "#{heading} #{msg.strip}" if code.nil? && msg
        "#{heading} #{msg.strip}. (#{code})"
      end

      def display_http_error?(code, msg)
        code.to_s != '200' && (code || msg)
      end

      def http_req_options(http_payload)
        {
          body: http_payload.payload,
          headers: {
            'Content-Type' => 'application/json',
            'NORAD-SIGNATURE' => http_payload.compute_signature
          }
        }
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
norad_beacon-0.1.7 lib/norad_beacon/api.rb