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 authored and wesleytodd committed Jan 23, 2025
1 parent 17c3999 commit e0f261e
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 @@ -146,7 +146,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 @@ -157,36 +156,40 @@ function contentstream (req, debug, inflate) {
})
}

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

var stream = createDecompressionStream(encoding, debug)
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 e0f261e

Please sign in to comment.