Sha256: b3fc52f68723b0381925ddb2c9d5a05a919751b959c09e36fe4f0fc88d8f6a38

Contents?: true

Size: 1.91 KB

Versions: 1

Compression:

Stored size: 1.91 KB

Contents

# frozen_string_literal: true

EasyPost::Connection = Struct.new(:uri, :config, keyword_init: true) do
  attr_reader :connection, :mutex

  def initialize(uri:, config:)
    super

    @mutex = Mutex.new
    @connection =
      if config[:proxy]
        proxy_uri = URI(config[:proxy])
        Net::HTTP.new(
          uri.host,
          uri.port,
          proxy_uri.host,
          proxy_uri.port,
          proxy_uri.user,
          proxy_uri.password,
        )
      else
        Net::HTTP.new(uri.host, uri.port)
      end

    connection.use_ssl = true

    config.each do |name, value|
      # Discrepancies between RestClient and Net::HTTP.
      case name
      when :verify_ssl
        name = :verify_mode
      when :timeout
        name = :read_timeout
      end

      # Handled in the creation of the client.
      if name == :proxy
        next
      end

      connection.public_send("#{name}=", value)
    end
  end

  # Make an HTTP request with Ruby's {Net::HTTP}
  #
  # @param method [Symbol] the HTTP Verb (get, method, put, post, etc.)
  # @param path [String] URI path of the resource
  # @param requested_api_key [String] ({EasyPost.api_key}) key set Authorization header.
  # @param body [String] (nil) body of the request
  # @raise [EasyPost::Error] if the response has a non-2xx status code
  # @return [Hash] JSON object parsed from the response body
  def call(method, path, api_key = nil, body = nil)
    request = Net::HTTP.const_get(method.capitalize).new(path)
    request.body = JSON.dump(EasyPost::Util.objects_to_ids(body)) if body

    EasyPost.default_headers.each_pair { |h, v| request[h] = v }
    request['Authorization'] = EasyPost.authorization(api_key) if api_key

    response = mutex.synchronize { connection.request(request) }

    EasyPost.parse_response(
      status: response.code.to_i,
      body: response.body,
      json: response['Content-Type'].start_with?('application/json'),
    )
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
easypost-4.1.1 lib/easypost/connection.rb