Skip to content

Commit

Permalink
brotli: set default quality to 4 closes #121
Browse files Browse the repository at this point in the history
  • Loading branch information
jonathanong committed Aug 18, 2021
1 parent 2271a41 commit 3d205cd
Show file tree
Hide file tree
Showing 4 changed files with 37 additions and 2 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ Setting `options[encoding] = false` will disable that encoding.
#### options<span></span>.br

[Brotli compression](https://en.wikipedia.org/wiki/Brotli) is supported in node v11.7.0+, which includes it natively.
As of v5.1.0, the default quality level is 4 for performance reasons.

### options.defaultEncoding\<String\>

Expand Down
12 changes: 12 additions & 0 deletions __tests__/defaults.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@

const assert = require('assert')
const zlib = require('zlib')

const createCompressMiddleware = require('..')

test('default brotli param quality should be 4', () => {
const middleware = createCompressMiddleware()
assert(Array.isArray(middleware.preferredEncodings))
assert(middleware.encodingOptions)
assert.strictEqual(middleware.encodingOptions.br[zlib.constants.BROTLI_PARAM_QUALITY], 4)
})
8 changes: 8 additions & 0 deletions lib/encodings.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,14 @@ Encodings.encodingMethods = {
br: zlib.createBrotliCompress
}

Encodings.encodingMethodDefaultOptions = {
gzip: {},
deflate: {},
br: {
[zlib.constants.BROTLI_PARAM_QUALITY]: 4
}
}

// how we treat `Accept-Encoding: *`
Encodings.wildcardAcceptEncoding = ['gzip', 'deflate']
// our preferred encodings
Expand Down
18 changes: 16 additions & 2 deletions lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,22 @@ module.exports = (options = {}) => {

// `options.br = false` would remove it as a preferred encoding
const preferredEncodings = Encodings.preferredEncodings.filter((encoding) => options[encoding] !== false && options[encoding] !== null)
const encodingOptions = {}
preferredEncodings.forEach((encoding) => {
encodingOptions[encoding] = {
...Encodings.encodingMethodDefaultOptions[encoding],
...(options[encoding] || {})
}
})

Object.assign(compressMiddleware, {
preferredEncodings,
encodingOptions
})

return compressMiddleware

return async (ctx, next) => {
async function compressMiddleware (ctx, next) {
ctx.vary('Accept-Encoding')

await next()
Expand Down Expand Up @@ -76,7 +90,7 @@ module.exports = (options = {}) => {
ctx.res.removeHeader('Content-Length')

const compress = Encodings.encodingMethods[encoding]
const stream = ctx.body = compress(options[encoding])
const stream = ctx.body = compress(encodingOptions[encoding])

if (body instanceof Stream) {
body.pipe(stream)
Expand Down

0 comments on commit 3d205cd

Please sign in to comment.