Class: Restforce::Middleware::Gzip

Inherits:
Restforce::Middleware show all
Defined in:
lib/restforce/middleware/gzip.rb

Overview

Middleware to uncompress GZIP compressed responses from Salesforce.

Constant Summary collapse

ACCEPT_ENCODING_HEADER =
'Accept-Encoding'
CONTENT_ENCODING_HEADER =
'Content-Encoding'
ENCODING =
'gzip'

Instance Method Summary collapse

Methods inherited from Restforce::Middleware

#client, #connection, #initialize

Constructor Details

This class inherits a constructor from Restforce::Middleware

Instance Method Details

#call(env) ⇒ Object



13
14
15
16
17
18
# File 'lib/restforce/middleware/gzip.rb', line 13

def call(env)
  env[:request_headers][ACCEPT_ENCODING_HEADER] = ENCODING if @options[:compress]
  @app.call(env).on_complete do |environment|
    on_complete(environment)
  end
end

#decompress(body) ⇒ Object

Internal: Decompresses a gzipped string.



30
31
32
33
34
35
36
# File 'lib/restforce/middleware/gzip.rb', line 30

def decompress(body)
  Zlib::GzipReader.new(StringIO.new(body)).read
rescue Zlib::GzipFile::Error
  # We thought the response was gzipped, but it wasn't. Return the original
  # body back to the caller. See https://github.com/restforce/restforce/issues/761.
  body
end

#gzipped?(env) ⇒ Boolean

Internal: Returns true if the response is gzipped.

Returns:

  • (Boolean)


25
26
27
# File 'lib/restforce/middleware/gzip.rb', line 25

def gzipped?(env)
  env[:response_headers][CONTENT_ENCODING_HEADER] == ENCODING
end

#on_complete(env) ⇒ Object



20
21
22
# File 'lib/restforce/middleware/gzip.rb', line 20

def on_complete(env)
  env[:body] = decompress(env[:body]) if gzipped?(env)
end