Skip to content

Commit

Permalink
Refactor decompression stream creation to remove code duplication
Browse files Browse the repository at this point in the history
  • Loading branch information
Phillip9587 committed Dec 6, 2024
1 parent 80fbb76 commit 34b8c7d
Showing 1 changed file with 26 additions and 23 deletions.
49 changes: 26 additions & 23 deletions lib/read.js
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,6 @@ function read (req, res, next, parse, debug, options) {
function contentstream (req, debug, inflate) {
var encoding = (req.headers['content-encoding'] || 'identity').toLowerCase()
var length = req.headers['content-length']
var stream

debug('content-encoding "%s"', encoding)

Expand All @@ -158,36 +157,40 @@ function contentstream (req, debug, inflate) {
})
}

if (encoding === 'identity') {
req.length = length
return req
}

var stream = createDecompressionStream(encoding)
req.pipe(stream)
return stream
}

/**
* Create a decompression stream for the given encoding.
* @param {string} encoding
* @param {function} debug
* @return {object}
* @api private
*/
function createDecompressionStream (encoding, debug) {
switch (encoding) {
case 'deflate':
stream = zlib.createInflate()
debug('inflate body')
req.pipe(stream)
break
return zlib.createInflate()
case 'gzip':
stream = zlib.createGunzip()
debug('gunzip body')
req.pipe(stream)
break
case 'identity':
stream = req
stream.length = length
break
return zlib.createGunzip()
case 'br':
stream = zlib.createBrotliDecompress()
debug('brotli decompress body')
req.pipe(stream)
break
}

if (stream === undefined) {
throw createError(415, 'unsupported content encoding "' + encoding + '"', {
encoding: encoding,
type: 'encoding.unsupported'
})
return zlib.createBrotliDecompress()
default:
throw createError(415, 'unsupported content encoding "' + encoding + '"', {
encoding: encoding,
type: 'encoding.unsupported'
})
}

return stream
}

/**
Expand Down

0 comments on commit 34b8c7d

Please sign in to comment.