Class: Tinify::Client

Inherits:
Object
  • Object
show all
Defined in:
lib/tinify/client.rb

Constant Summary collapse

API_ENDPOINT =
"https://api.tinify.com".freeze
RETRY_COUNT =
1
RETRY_DELAY =
500
USER_AGENT =
"Tinify/#{VERSION} Ruby/#{RUBY_VERSION}p#{RUBY_PATCHLEVEL} (#{defined?(RUBY_ENGINE) ? RUBY_ENGINE : "unknown"})".freeze
CA_BUNDLE =
File.expand_path("../../data/cacert.pem", __FILE__).freeze

Instance Method Summary collapse

Constructor Details

#initialize(key, app_identifier = nil, proxy = nil) ⇒ Client

Returns a new instance of Client.



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/tinify/client.rb', line 15

def initialize(key, app_identifier = nil, proxy = nil)
  begin
    @client = HTTPClient.new(proxy)
  rescue ArgumentError => err
    raise ConnectionError.new("Invalid proxy: #{err.message}")
  end

  @client.base_url = API_ENDPOINT
  @client.default_header = { "User-Agent" => [USER_AGENT, app_identifier].compact.join(" ") }

  @client.force_basic_auth = true
  @client.set_auth("/", "api", key)

  @client.ssl_config.clear_cert_store
  @client.ssl_config.add_trust_ca(CA_BUNDLE)
end

Instance Method Details

#request(method, url, body = nil) ⇒ Object



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/tinify/client.rb', line 32

def request(method, url, body = nil)
  header = {}
  if Hash === body
    if body.empty?
      body = nil
    else
      body = JSON.generate(body)
      header["Content-Type"] = "application/json"
    end
  end

  RETRY_COUNT.downto(0) do |retries|
    sleep RETRY_DELAY / 1000.0 if retries < RETRY_COUNT

    begin
      response = @client.request(method, url, body: body, header: header)
    rescue HTTPClient::TimeoutError => err
      next if retries > 0
      raise ConnectionError.new("Timeout while connecting")
    rescue StandardError => err
      next if retries > 0
      raise ConnectionError.new("Error while connecting: #{err.message}")
    end

    if count = response.headers["Compression-Count"]
      Tinify.compression_count = count.to_i
    end

    return response if response.ok?

    details = begin
      JSON.parse(response.body)
    rescue StandardError => err
      {"message" => "Error while parsing response: #{err.message}", "error" => "ParseError"}
    end
    next if retries > 0 and response.status >= 500
    raise Error.create(details["message"], details["error"], response.status)
  end
end