Skip to content

Commit

Permalink
Merge pull request #12 from michal-kazmierczak/master
Browse files Browse the repository at this point in the history
Automatically decompress the body
  • Loading branch information
marcelobarreto authored Mar 20, 2023
2 parents f2f259e + 48415f2 commit a2190eb
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 2 deletions.
17 changes: 16 additions & 1 deletion lib/postgrest/responses/base_response.rb
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,12 @@ def status_text
end

def data
error ? [] : safe_json_parse(response.body)
return [] if error

body = response.body
body = decompress(body) if compressed_body?

safe_json_parse(body)
end
alias as_json data

Expand All @@ -50,6 +55,16 @@ def safe_json_parse(json)
rescue TypeError, JSON::ParserError
{}
end

def decompress(body)
gz = Zlib::GzipReader.new(StringIO.new(body))
gz.read
end

def compressed_body?
# https://ruby-doc.org/3.2.1/stdlibs/net/Net/HTTP.html#class-Net::HTTP-label-Compression
response['content-encoding'] == 'gzip' && response['content-range']
end
end
end
end
23 changes: 22 additions & 1 deletion spec/postgrest/responses/base_response_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ module Postgrest
before do
allow(response).to receive(:is_a?).and_return(true)
allow(response).to receive(:body).and_return(response_body)
allow(response).to receive(:[]).and_return({})
end

describe '#error' do
Expand Down Expand Up @@ -80,6 +81,26 @@ module Postgrest

it { expect(subject.data).to eq({}) }
end

context 'when response body was compressed' do
subject { described_class.new(request, response) }

let(:response_body) do
data = { success: true, foo: :bar }.to_json
gz = Zlib::GzipWriter.new(StringIO.new)
gz << data
gz.close.string
end

before do
allow(response).to receive(:[]).with('content-encoding').and_return('gzip')
allow(response).to receive(:[]).with('content-range').and_return('0-999/*')
end

it 'decompresses the body' do
expect(subject.data).to eq({ 'success' => true, 'foo' => 'bar' })
end
end
end

describe '#params' do
Expand All @@ -90,4 +111,4 @@ module Postgrest
end
end
end
end
end

0 comments on commit a2190eb

Please sign in to comment.