Sha256: 1c9b2d206ce9ff0179284e90f56e81a192376637ac0de6390470996de7da4d7c

Contents?: true

Size: 1.47 KB

Versions: 2

Compression:

Stored size: 1.47 KB

Contents

# frozen_string_literal: true

require 'net/http'
require_relative '../options'

class Valvat
  class Lookup
    class Base
      def initialize(vat, options = {})
        @vat = Valvat(vat)
        @options = Valvat::Options(options)
        @requester = @options[:requester] && Valvat(@options[:requester])
        @rate_limit = @options[:rate_limit]
      end

      def perform
        response = fetch(endpoint_uri)

        case response
        when Net::HTTPSuccess
          parse(response.body)
        else
          { error: Valvat::HTTPError.new(response.code, self.class) }
        end
      end

      private

      def endpoint_uri
        raise NotImplementedError
      end

      def build_request(uri)
        raise NotImplementedError
      end

      def parse(body)
        raise NotImplementedError
      end

      def fetch(uri, limit = 0)
        response = send_request(uri)

        if response == Net::HTTPRedirection && limit < @rate_limit
          fetch(URI.parse(response['Location']), limit + 1)
        else
          response
        end
      rescue Errno::ECONNRESET, IOError
        raise if limit > @rate_limit

        fetch(uri, limit + 1)
      end

      def send_request(uri)
        request = build_request(uri)

        Net::HTTP.start(uri.host, uri.port, options_for(uri)) do |http|
          http.request(request)
        end
      end

      def options_for(uri)
        @options[:http].merge({ use_ssl: URI::HTTPS === uri })
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
valvat-2.0.1 lib/valvat/lookup/base.rb
valvat-2.0.0 lib/valvat/lookup/base.rb