Skip to content

Commit

Permalink
Add "decompressStream" utility
Browse files Browse the repository at this point in the history
  • Loading branch information
kettanaito committed Jul 26, 2024
1 parent a6ca426 commit 3e89cd4
Showing 1 changed file with 32 additions and 17 deletions.
49 changes: 32 additions & 17 deletions lib/web/fetch/decompress.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,20 +10,7 @@ const { createInflate } = require('./util')
* @returns {ReadableStream<Uint8Array> | null}
*/
function decompress (request, response) {
const contentEncoding = response.headers.get('content-encoding')

if (!contentEncoding) {
return response.body
}

// https://www.rfc-editor.org/rfc/rfc7231#section-3.1.2.1
// "All content-coding values are case-insensitive..."
const codings = contentEncoding
.toLowerCase()
.split(',')
.map((coding) => coding.trim())

if (codings.length === 0) {
if (response.body === null) {
return response.body
}

Expand All @@ -41,6 +28,33 @@ function decompress (request, response) {
return response.body
}

return decompressStream(
response.body,
response.headers.get('content-encoding')
)
}

/**
* Decompress the given stream based on the "Content-Encoding" response header.
* @param {ReadableStream<Uint8Array>} stream
* @param {string | null} contentEncoding The value of the "Content-Encoding" response header.
*/
function decompressStream (stream, contentEncoding) {
if (!contentEncoding) {
return stream
}

// https://www.rfc-editor.org/rfc/rfc7231#section-3.1.2.1
// "All content-coding values are case-insensitive..."
const codings = contentEncoding
.toLowerCase()
.split(',')
.map((coding) => coding.trim())

if (codings.length === 0) {
return stream
}

const decoders = []

for (let i = codings.length - 1; i >= 0; --i) {
Expand Down Expand Up @@ -69,12 +83,13 @@ function decompress (request, response) {
}

if (decoders.length === 0) {
return response.body
return stream
}

return pipeline(response.body, ...decoders, () => {})
return pipeline(stream, ...decoders, () => {})
}

module.exports = {
decompress
decompress,
decompressStream
}

0 comments on commit 3e89cd4

Please sign in to comment.