module Percy::Client::Connection

Public Instance Methods

_api_version() click to toggle source
# File lib/percy/client/connection.rb, line 146
def _api_version
  config.api_url.match(/\w+$/).to_s
end
_headers() click to toggle source
# File lib/percy/client/connection.rb, line 117
def _headers
  {
    'Content-Type' => 'application/vnd.api+json',
    'User-Agent' => _user_agent,
  }
end
_reset_user_agent() click to toggle source
# File lib/percy/client/connection.rb, line 142
def _reset_user_agent
  @_user_agent = nil
end
_ruby_version() click to toggle source
# File lib/percy/client/connection.rb, line 150
def _ruby_version
  "#{RUBY_VERSION}p#{RUBY_PATCHLEVEL}"
end
_user_agent() click to toggle source
# File lib/percy/client/connection.rb, line 124
def _user_agent
  @_user_agent ||= begin
    client = [
      "Percy/#{_api_version}",
      client_info,
      "percy-client/#{VERSION}",
    ].compact.join(' ')

    environment = [
      environment_info,
      "ruby/#{_ruby_version}",
      Percy::Client::Environment.ci_info,
    ].compact.join('; ')

    "#{client} (#{environment})"
  end
end
connection() click to toggle source
# File lib/percy/client/connection.rb, line 50
def connection
  return @connection if defined?(@connection)

  parsed_uri = URI.parse(config.api_url)
  base_url = "#{parsed_uri.scheme}://#{parsed_uri.host}:#{parsed_uri.port}"

  @connection = Faraday.new(url: base_url) do |faraday|
    faraday.request :token_auth, config.access_token if config.access_token
    faraday.use Percy::Client::Connection::NiceErrorMiddleware
    faraday.adapter :excon
  end

  @connection
end
get(path, options = {}) click to toggle source
# File lib/percy/client/connection.rb, line 65
def get(path, options = {})
  retries = options[:retries] || 3

  begin
    response = connection.get do |request|
      request.url(path)
      request.headers.merge! _headers
    end
  rescue Faraday::TimeoutError
    raise Percy::Client::TimeoutError
  rescue Faraday::ConnectionFailed
    raise Percy::Client::ConnectionFailed
  rescue Percy::Client::ServerError => e
    # Retry on 5XX errors.
    if (retries -= 1) >= 0
      sleep(rand(1..3))
      retry
    end
    raise e
  end
  JSON.parse(response.body)
end
post(path, data, options = {}) click to toggle source
# File lib/percy/client/connection.rb, line 88
def post(path, data, options = {})
  retries = options[:retries] || 3

  begin
    response = connection.post do |request|
      request.url(path)
      request.headers.merge! _headers
      request.body = data.to_json
    end
  rescue Faraday::TimeoutError
    if (retries -= 1) >= 0
      retry
    end
    raise Percy::Client::TimeoutError
  rescue Faraday::ConnectionFailed
    raise Percy::Client::ConnectionFailed
  rescue Percy::Client::ServerError => e
    # Retry on 5XX errors.
    if (retries -= 1) >= 0
      sleep(rand(1..3))
      retry
    end

    raise e
  end

  JSON.parse(response.body)
end