Module: Percy::Client::Connection

Included in:
Percy::Client
Defined in:
lib/percy/client/connection.rb

Defined Under Namespace

Classes: NiceErrorMiddleware, NoCookiesHTTPClientAdapter

Instance Method Summary collapse

Instance Method Details

#connectionObject



31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/percy/client/connection.rb', line 31

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::NoCookiesHTTPClientAdapter
    faraday.use Percy::Client::Connection::NiceErrorMiddleware
  end
  @connection
end

#get(path) ⇒ Object



44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/percy/client/connection.rb', line 44

def get(path)
  retries = 3
  begin
    response = connection.get do |request|
      request.url(path)
      request.headers['Content-Type'] = 'application/vnd.api+json'
    end
  rescue Faraday::TimeoutError
    raise Percy::Client::TimeoutError
  rescue Faraday::ConnectionFailed
    raise Percy::Client::ConnectionFailed
  rescue Percy::Client::HttpError => e
    # Retry on 502 errors.
    if e.status == 502 && (retries -= 1) >= 0
      sleep(rand(1..3))
      retry
    end
    raise e
  end
  JSON.parse(response.body)
end

#post(path, data) ⇒ Object



66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
# File 'lib/percy/client/connection.rb', line 66

def post(path, data)
  retries = 3
  begin
    response = connection.post do |request|
      request.url(path)
      request.headers['Content-Type'] = 'application/vnd.api+json'
      request.body = data.to_json
    end
  rescue Faraday::TimeoutError
    raise Percy::Client::TimeoutError
  rescue Faraday::ConnectionFailed
    raise Percy::Client::ConnectionFailed
  rescue Percy::Client::HttpError => e
    # Retry on 502 errors.
    if e.status == 502 && (retries -= 1) >= 0
      sleep(rand(1..3))
      retry
    end
    raise e
  end
  JSON.parse(response.body)
end