Skip to content

Commit 92e52a7

Browse files
mcollinaEomm
andauthored
Do not set the compress onSend hook twice (#141)
* Do not set the compress onSend hook twice Fixes #140 * fixup * Update test/test-routes-compress.js Co-authored-by: Manuel Spigolon <[email protected]> Co-authored-by: Manuel Spigolon <[email protected]>
1 parent 64ec82a commit 92e52a7

File tree

2 files changed

+39
-0
lines changed

2 files changed

+39
-0
lines changed

index.js

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,8 @@ const { inherits, format } = require('util')
1919
const InvalidRequestEncodingError = createError('FST_CP_ERR_INVALID_CONTENT_ENCODING', 'Unsupported Content-Encoding: %s', 415)
2020
const InvalidRequestCompressedPayloadError = createError('FST_CP_ERR_INVALID_CONTENT', 'Could not decompress the request payload using the provided encoding', 400)
2121

22+
const compressAdded = Symbol('fastify-compress.added')
23+
2224
function compressPlugin (fastify, opts, next) {
2325
const globalCompressParams = processCompressParams(opts)
2426
const globalDecompressParams = processDecompressParams(opts)
@@ -179,6 +181,16 @@ function processDecompressParams (opts) {
179181
}
180182

181183
function buildRouteCompress (fastify, params, routeOptions, decorateOnly) {
184+
// This methods works by altering the routeOptions, it has side effects.
185+
// There is the possibility that the same options are set for more than
186+
// one route, so we just need to make sure that the hook is addded only
187+
// once.
188+
if (routeOptions[compressAdded]) {
189+
return
190+
}
191+
192+
routeOptions[compressAdded] = true
193+
182194
// In order to provide a compress method with the same parameter set as the route itself has
183195
// we do the decorate the reply at the start of the request
184196
if (Array.isArray(routeOptions.onRequest)) {

test/test-routes-compress.js

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -255,3 +255,30 @@ test('should throw an error on invalid compression setting', t => {
255255
t.strictEqual(err.message, 'Unknown value for route compress configuration')
256256
})
257257
})
258+
259+
test('avoid double onSend', t => {
260+
t.plan(2)
261+
262+
const server = Fastify()
263+
264+
server.register(compressPlugin, {
265+
threshold: 0
266+
})
267+
268+
server.register(async function (server) {
269+
server.get('/', async (req, _) => {
270+
return { hi: true }
271+
})
272+
}, { prefix: '/test' })
273+
274+
server.inject({
275+
url: '/test',
276+
method: 'GET',
277+
headers: {
278+
'accept-encoding': 'br'
279+
}
280+
}, (err, res) => {
281+
t.error(err)
282+
t.deepEqual(JSON.parse(zlib.brotliDecompressSync(res.rawPayload)), { hi: true })
283+
})
284+
})

0 commit comments

Comments
 (0)