Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support passing zlibOptions and brotliOptions #113

Merged
merged 2 commits into from
Jun 26, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,24 @@ fastify.register(
)
```

### brotliOptions and zlibOptions

You can tune compression by setting the `brotliOptions` and `zlibOptions` properties. These properties are passed directly to native node `zlib` methods, so they should match the corresponding [class](https://nodejs.org/api/zlib.html#zlib_class_brotlioptions) [definitions](https://nodejs.org/api/zlib.html#zlib_class_options).

```javascript
server.register(fastifyCompress, {
brotliOptions: {
params: {
[zlib.constants.BROTLI_PARAM_MODE]: zlib.constants.BROTLI_MODE_TEXT, // useful for APIs that primarily return text
[zlib.constants.BROTLI_PARAM_QUALITY]: 4, // default is 11, max is 11, min is 0
},
},
zlibOptions: {
level: 9, // default is 9, max is 9, min is 0
}
});
```

## Usage - Decompress request payloads

This plugin adds a `preParsing` hook that decompress the request payload according to the `content-encoding` request header.
Expand Down
5 changes: 4 additions & 1 deletion index.d.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import { FastifyPlugin, FastifyReply, FastifyRequest, RawServerBase } from 'fastify';
import { Input, InputObject } from 'into-stream';
import { Stream } from 'stream';
import { BrotliOptions, ZlibOptions } from 'zlib';

declare module "fastify" {
interface FastifyReplyInterface {
interface FastifyReply {
compress(input: Stream | Input | InputObject): void;
}
}
Expand All @@ -15,6 +16,8 @@ export interface FastifyCompressOptions {
threshold?: number
customTypes?: RegExp
zlib?: NodeModule
brotliOptions?: BrotliOptions
zlibOptions?: ZlibOptions
inflateIfDeflated?: boolean
onUnsupportedEncoding?: (encoding: string, request: FastifyRequest<RawServerBase>, reply: FastifyReply<RawServerBase>) => string | Buffer | Stream
encodings?: Array<EncodingToken>
Expand Down
15 changes: 8 additions & 7 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -110,19 +110,21 @@ function processCompressParams (opts) {
global: (typeof opts.global === 'boolean') ? opts.global : true
}

params.brotliOptions = opts.brotliOptions
params.zlibOptions = opts.zlibOptions
params.onUnsupportedEncoding = opts.onUnsupportedEncoding
params.inflateIfDeflated = opts.inflateIfDeflated === true
params.threshold = typeof opts.threshold === 'number' ? opts.threshold : 1024
params.compressibleTypes = opts.customTypes instanceof RegExp ? opts.customTypes : /^text\/|\+json$|\+text$|\+xml$|octet-stream$/
params.compressStream = {
br: (opts.zlib || zlib).createBrotliCompress || zlib.createBrotliCompress,
gzip: (opts.zlib || zlib).createGzip || zlib.createGzip,
deflate: (opts.zlib || zlib).createDeflate || zlib.createDeflate
br: () => ((opts.zlib || zlib).createBrotliCompress || zlib.createBrotliCompress)(params.brotliOptions),
gzip: () => ((opts.zlib || zlib).createGzip || zlib.createGzip)(params.zlibOptions),
deflate: () => ((opts.zlib || zlib).createDeflate || zlib.createDeflate)(params.zlibOptions)
}
params.uncompressStream = {
br: (opts.zlib || zlib).createBrotliDecompress || zlib.createBrotliDecompress,
gzip: (opts.zlib || zlib).createGunzip || zlib.createGunzip,
deflate: (opts.zlib || zlib).createInflate || zlib.createInflate
br: () => ((opts.zlib || zlib).createBrotliDecompress || zlib.createBrotliDecompress)(params.brotliOptions),
gzip: () => ((opts.zlib || zlib).createGunzip || zlib.createGunzip)(params.zlibOptions),
deflate: () => ((opts.zlib || zlib).createInflate || zlib.createInflate)(params.zlibOptions)
}

const supportedEncodings = ['br', 'gzip', 'deflate', 'identity']
Expand Down Expand Up @@ -321,7 +323,6 @@ function buildRouteDecompress (fastify, params, routeOptions) {
function compress (params) {
return function (payload) {
if (payload == null) {
this.log.debug('compress: missing payload')
this.send(new Error('Internal server error'))
return
}
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
"@types/node": "^14.0.1",
"@typescript-eslint/parser": "^3.0.0",
"eslint-plugin-typescript": "^0.14.0",
"fastify": "^3.0.0-rc.3",
"fastify": "^3.0.0-rc.4",
"jsonstream": "^1.0.3",
"pre-commit": "^1.2.2",
"standard": "^14.3.1",
Expand Down
9 changes: 8 additions & 1 deletion test/index.test-d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,21 @@ app.register(fastifyCompress, {
global: true,
threshold: 10,
zlib: zlib,
brotliOptions: {
params: {
[zlib.constants.BROTLI_PARAM_MODE]: zlib.constants.BROTLI_MODE_TEXT,
[zlib.constants.BROTLI_PARAM_QUALITY]: 4
}
},
zlibOptions: { level: 1 },
inflateIfDeflated: true,
customTypes: /x-protobuf$/,
encodings: ['gzip', 'br', 'identity', 'deflate'],
requestEncodings: ['gzip', 'br', 'identity', 'deflate'],
forceRequestEncoding: 'gzip'
})

const appWithoutGlobal = fastify();
const appWithoutGlobal = fastify()

appWithoutGlobal.register(fastifyCompress, { global: false })

Expand Down
95 changes: 95 additions & 0 deletions test/test-global-compress.js
Original file line number Diff line number Diff line change
Expand Up @@ -1597,3 +1597,98 @@ test('Should not compress mime types with undefined compressible values', t => {
t.strictEqual(res.payload, 'hello')
})
})

test('Should send data compressed according to brotliOptions', t => {
t.plan(3)
const fastify = Fastify()
const brotliOptions = {
params: {
[zlib.constants.BROTLI_PARAM_MODE]: zlib.constants.BROTLI_MODE_TEXT,
[zlib.constants.BROTLI_PARAM_QUALITY]: 4
}
}

fastify.register(compressPlugin, {
global: false,
brotliOptions
})

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

fastify.inject({
url: '/',
method: 'GET',
headers: {
'accept-encoding': 'br'
}
}, (err, res) => {
t.error(err)
t.strictEqual(res.headers['content-encoding'], 'br')
const file = readFileSync('./package.json', 'utf8')
const payload = zlib.brotliDecompressSync(res.rawPayload, brotliOptions)
t.strictEqual(payload.toString('utf-8'), file)
})
})

test('Should send data deflated according to zlibOptions', t => {
t.plan(3)
const fastify = Fastify()
const zlibOptions = {
level: 1,
dictionary: Buffer.from('fastifycompress')
}

fastify.register(compressPlugin, {
global: false,
zlibOptions
})

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

fastify.inject({
url: '/',
method: 'GET',
headers: {
'accept-encoding': 'deflate'
}
}, (err, res) => {
t.error(err)
t.strictEqual(res.headers['content-encoding'], 'deflate')
const fileBuffer = readFileSync('./package.json')
t.same(res.rawPayload, zlib.deflateSync(fileBuffer, zlibOptions))
})
})

test('Should send data gzipped according to zlibOptions', t => {
t.plan(3)
const fastify = Fastify()
const zlibOptions = {
level: 1
}

fastify.register(compressPlugin, {
global: false,
zlibOptions
})

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

fastify.inject({
url: '/',
method: 'GET',
headers: {
'accept-encoding': 'gzip'
}
}, (err, res) => {
t.error(err)
t.strictEqual(res.headers['content-encoding'], 'gzip')
const fileBuffer = readFileSync('./package.json')
t.same(res.rawPayload, zlib.gzipSync(fileBuffer, zlibOptions))
})
})