class Elastomer::Middleware::Compress

Request middleware that compresses request bodies with GZip for supported versions of Elasticsearch.

It will only compress when there is a request body that is a String. This middleware should be inserted after JSON serialization.

Constants

CONTENT_ENCODING
GZIP
MIN_BYTES_FOR_COMPRESSION

An Ethernet packet can hold 1500 bytes. No point in compressing anything smaller than that (plus some wiggle room).

Attributes

compression[R]

Public Class Methods

new(app, options = {}) click to toggle source

options - The Hash of “keyword” arguments.

:compression - the compression level (0-9, default Zlib::DEFAULT_COMPRESSION)
Calls superclass method
# File lib/elastomer/middleware/compress.rb, line 21
def initialize(app, options = {})
  super(app)
  @compression = options[:compression] || Zlib::DEFAULT_COMPRESSION
end

Public Instance Methods

call(env) click to toggle source
# File lib/elastomer/middleware/compress.rb, line 26
def call(env)
  if body = env[:body]
    if body.is_a?(String) && body.bytesize > MIN_BYTES_FOR_COMPRESSION
      output = StringIO.new
      output.set_encoding("BINARY")
      gz = Zlib::GzipWriter.new(output, compression, Zlib::DEFAULT_STRATEGY)
      gz.write(env[:body])
      gz.close
      env[:body] = output.string
      env[:request_headers][CONTENT_ENCODING] = GZIP
    end
  end

  @app.call(env)
end