Skip to content

Commit

Permalink
Fix it incorrectly modifying the original response
Browse files Browse the repository at this point in the history
And correctly remove `content-length` header.

Fixes #28 (comment)

Fixes #37
  • Loading branch information
sindresorhus committed May 28, 2024
1 parent d935d94 commit 8e713c3
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 3 deletions.
12 changes: 9 additions & 3 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,11 @@ export default function decompressResponse(response) {
return response;
}

delete response.headers['content-encoding'];

let isEmpty = true;
let finalStream = new PassThroughStream();

// Clone headers to avoid modifying the original response headers
const headers = {...response.headers};

function handleContentEncoding(data) {
const decompressStream = contentEncoding === 'br'
Expand Down Expand Up @@ -51,7 +53,7 @@ export default function decompressResponse(response) {
},
});

const finalStream = new PassThroughStream({
finalStream = new PassThroughStream({
autoDestroy: false,
destroy(error, callback) {
response.destroy();
Expand All @@ -60,6 +62,10 @@ export default function decompressResponse(response) {
},
});

delete headers['content-encoding'];
delete headers['content-length'];
finalStream.headers = headers;

mimicResponse(response, finalStream);
response.pipe(checker);

Expand Down
14 changes: 14 additions & 0 deletions test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -153,3 +153,17 @@ test('passthrough on non-compressed data', async t => {

t.is(await getStream(response), fixture);
});

test('original response retains content-encoding and content-length headers', async t => {
const originalResponse = await httpGetP(server.url);
const decompressedResponse = decompressResponse(originalResponse);

t.is(originalResponse.headers['content-encoding'], 'gzip');
t.truthy(originalResponse.headers['content-length']);
t.is(decompressedResponse.headers['content-encoding'], undefined);
t.is(decompressedResponse.headers['content-length'], undefined);

decompressedResponse.setEncoding('utf8');

t.is(await getStream(decompressedResponse), fixture);
});

0 comments on commit 8e713c3

Please sign in to comment.