diff --git a/lib/baza-rb.rb b/lib/baza-rb.rb index 2c021934..60549f83 100644 --- a/lib/baza-rb.rb +++ b/lib/baza-rb.rb @@ -16,6 +16,7 @@ require 'tempfile' require 'typhoeus' require 'zlib' +require_relative 'baza-rb/compress' require_relative 'baza-rb/version' # Ruby client for the Zerocracy API. @@ -35,6 +36,8 @@ class BazaRb DEFAULT_CHUNK_SIZE = 1_000_000 + include Compress + # When the server failed (503). class ServerFailure < StandardError; end @@ -594,32 +597,6 @@ def headers } end - # Decompress gzipped data. - # - # @param [String] data The gzipped data to decompress - # @return [String] The decompressed data - def unzip(data) - Zlib::GzipReader.new(StringIO.new(data)).read - rescue Zlib::GzipFile::Error => e - raise(BadCompression, "Failed to unzip #{data.bytesize} bytes: #{e.message}") - end - - # Compress request parameters with gzip. - # - # @param [Hash] params The request parameters with :body and :headers keys - # @return [Hash] The modified parameters with compressed body and updated headers - def zipped(params) - io = StringIO.new - gz = Zlib::GzipWriter.new(io) - gz.write(params.fetch(:body)) - gz.close - body = io.string - params.merge( - body:, - headers: params.fetch(:headers).merge({ 'Content-Encoding' => 'gzip', 'Content-Length' => body.bytesize }) - ) - end - # Build the base URI for API requests. # # @return [Iri] The base URI object diff --git a/lib/baza-rb/compress.rb b/lib/baza-rb/compress.rb new file mode 100644 index 00000000..914fa3cd --- /dev/null +++ b/lib/baza-rb/compress.rb @@ -0,0 +1,47 @@ +# frozen_string_literal: true + +# SPDX-FileCopyrightText: Copyright (c) 2024-2026 Zerocracy +# SPDX-License-Identifier: MIT + +require 'stringio' +require 'zlib' + +# Compression helpers for BazaRb. +# +# Provides gzip compression and decompression for request bodies +# and response data. +# +# Author:: Yegor Bugayenko (yegor256@gmail.com) +# Copyright:: Copyright (c) 2024-2026 Yegor Bugayenko +# License:: MIT +class BazaRb + # Compression helpers. + module Compress + # Decompress gzipped data. + # + # @param [String] data The gzipped data to decompress + # @return [String] The decompressed data + # @raise [BadCompression] If the data is not valid gzip + def unzip(data) + Zlib::GzipReader.new(StringIO.new(data)).read + rescue Zlib::GzipFile::Error => e + raise(BadCompression, "Failed to unzip #{data.bytesize} bytes: #{e.message}") + end + + # Compress request parameters with gzip. + # + # @param [Hash] params The request parameters with :body and :headers keys + # @return [Hash] The modified parameters with compressed body and updated headers + def zipped(params) + io = StringIO.new + gz = Zlib::GzipWriter.new(io) + gz.write(params.fetch(:body)) + gz.close + body = io.string + params.merge( + body:, + headers: params.fetch(:headers).merge({ 'Content-Encoding' => 'gzip', 'Content-Length' => body.bytesize }) + ) + end + end +end