Skip to content

Commit

Permalink
fix: content encoding priorities (#258)
Browse files Browse the repository at this point in the history
* fix: content encoding priorities

* test: add corresponding tests

---------

Co-authored-by: Shishir Karanth <shishira.k@cimpress.com>
  • Loading branch information
shishir-karanth and Shishir Karanth committed Mar 27, 2023
1 parent d789e44 commit 9b33bfa
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 3 deletions.
4 changes: 2 additions & 2 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,7 @@ function processCompressParams (opts) {
params.encodings = Array.isArray(opts.encodings)
? supportedEncodings
.filter(encoding => opts.encodings.includes(encoding))
.sort((a, b) => opts.encodings.indexOf(a) - supportedEncodings.indexOf(b))
.sort((a, b) => opts.encodings.indexOf(a) - opts.encodings.indexOf(b))
: supportedEncodings

return params
Expand Down Expand Up @@ -174,7 +174,7 @@ function processDecompressParams (opts) {
params.encodings = Array.isArray(opts.requestEncodings)
? supportedEncodings
.filter(encoding => opts.requestEncodings.includes(encoding))
.sort((a, b) => opts.requestEncodings.indexOf(a) - supportedEncodings.indexOf(b))
.sort((a, b) => opts.requestEncodings.indexOf(a) - opts.requestEncodings.indexOf(b))
: supportedEncodings

if (opts.forceRequestEncoding) {
Expand Down
31 changes: 30 additions & 1 deletion test/global-compress.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -2703,7 +2703,7 @@ test('It should sort and follow custom `encodings` options', async (t) => {
const fastify = Fastify()
await fastify.register(compressPlugin, {
global: true,
encodings: ['gzip', 'br']
encodings: ['br', 'gzip']
})

fastify.get('/', (request, reply) => {
Expand All @@ -2725,6 +2725,35 @@ test('It should sort and follow custom `encodings` options', async (t) => {
t.equal(payload.toString('utf-8'), file)
})

test('It should sort and prefer the order of custom `encodings` options', async (t) => {
t.plan(2)

const fastify = Fastify()
await fastify.register(compressPlugin, {
global: true,
encodings: ['gzip', 'deflate', 'br']
})

fastify.get('/', (request, reply) => {
reply
.type('text/plain')
.compress(createReadStream('./package.json'))
})

const response = await fastify.inject({
url: '/',
method: 'GET',
headers: {
'accept-encoding': 'hello,gzip,br'
}
})

const file = readFileSync('./package.json', 'utf8')
const payload = zlib.gunzipSync(response.rawPayload)
t.equal(response.headers['content-encoding'], 'gzip')
t.equal(payload.toString('utf-8'), file)
})

test('It should sort and follow custom `requestEncodings` options', async (t) => {
t.plan(2)

Expand Down

0 comments on commit 9b33bfa

Please sign in to comment.