Why Gemfury? Push, build, and install  RubyGems npm packages Python packages Maven artifacts PHP packages Go Modules Debian packages RPM packages NuGet packages

Repository URL to install this package:

Details    
Size: Mime:
module FieldLocateApi
  # Defines HTTP request methods
  module Request
    # Perform an HTTP GET request
    def get(path, options = {})
      request(:get, path, options)
    end

    # Perform an HTTP POST request
    def post(path, options = {})
      request(:post, path, options)
    end

    private

    # Perform an HTTP request
    def request(method, path, options)
      begin
        response = connection.send(method) do |request|
          case method.to_sym
          when :get
            formatted_options = format_options(options)
            request.url(path, formatted_options)
          when :post, :put
            # Currently not supported
          end
          request.options.timeout = 30        # open / read timeout is five seconds.
          request.options.open_timeout = 60   # connection open timeout is two seconds.
        end
      rescue Faraday::ConnectionFailed => e
        raise ConnectionError, e
      rescue Faraday::TimeoutError => e
        raise TimeoutError, e
      rescue Faraday::ResourceNotFound => e
        raise NotFoundError, e
      rescue Faraday::ParsingError => e
        if e.message.include?('Entity with Key') && e.message.include?('does not exist')
          raise NotFoundError, e
        elsif e.message.include?('Request is forbidden.') || e.message.include?('Access is denied')
          raise UnauthorizedError, 'API Key is incorrect'
        else
          raise ParseError, e
        end
      rescue Faraday::SSLError => e
        raise SSLError, e
      rescue StandardError => e
        raise Error, e
      end

      Response.create(response.body)
    end

    def request_params
      %i[pageSize pageStartIndex extAcctUpdateNeeded extAcctRef createdAfter q]
    end

    def default_page_size
      100
    end

    # Format the options before you send them off to FieldLocateApi
    def format_options(options)
      request_params.each do |rp|
        options[rp] = options[rp] if options.key?(rp)
      end

      if options.key?(:pageNumber)
        page_size = options[:pageSize].to_i.zero? ? default_page_size : options[:pageSize].to_i
        options[:pageStartIndex] = (page_size * (options[:pageNumber].to_i - 1))
        options[:pageSize] = page_size
      end

      client = self
      options[:api_key] = client.api_key
      options
    end
  end
end