|
| 1 | +'use strict' |
| 2 | + |
| 3 | +const { test } = require('node:test') |
| 4 | +const zlib = require('node:zlib') |
| 5 | +const Fastify = require('fastify') |
| 6 | +const fastifyCompress = require('../..') |
| 7 | + |
| 8 | +const largeJsonString = JSON.stringify({ |
| 9 | + text: 'Lorem ipsum dolor sit amet. '.repeat(2048), |
| 10 | +}) |
| 11 | + |
| 12 | +async function routes (fastify) { |
| 13 | + fastify.route({ |
| 14 | + method: 'GET', |
| 15 | + url: '/api/compress-test', |
| 16 | + handler: async function (_request, reply) { |
| 17 | + reply.type('application/json') |
| 18 | + return reply.compress(largeJsonString) |
| 19 | + } |
| 20 | + }) |
| 21 | +} |
| 22 | + |
| 23 | +test('should compress large payload without premature close', async (t) => { |
| 24 | + const fastify = Fastify() |
| 25 | + await fastify.register(fastifyCompress, { encodings: ['gzip'], global: true }) |
| 26 | + await fastify.register(routes) |
| 27 | + |
| 28 | + const response = await fastify.inject({ |
| 29 | + url: '/api/compress-test', |
| 30 | + method: 'GET', |
| 31 | + headers: { 'accept-encoding': 'gzip' } |
| 32 | + }) |
| 33 | + |
| 34 | + t.assert.equal(response.statusCode, 200) |
| 35 | + t.assert.equal(response.headers['content-encoding'], 'gzip') |
| 36 | + t.assert.ok( |
| 37 | + response.rawPayload.length > 0, |
| 38 | + `Expected compressed response body, got ${response.rawPayload.length} bytes` |
| 39 | + ) |
| 40 | + |
| 41 | + const decompressed = zlib.gunzipSync(response.rawPayload) |
| 42 | + t.assert.equal(decompressed.toString('utf-8'), largeJsonString) |
| 43 | +}) |
0 commit comments