Skip to content

Commit 295f5ee

Browse files
committed
Simplify compress pipeline
1 parent c267506 commit 295f5ee

File tree

2 files changed

+17
-28
lines changed

2 files changed

+17
-28
lines changed

src/compression/compress.ts

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { Readable } from 'node:stream';
1+
import { Transform } from 'node:stream';
22
import zlib from 'node:zlib';
33
import type { ReadableStream } from 'stream/web';
44
import { Headers, Response } from 'undici';
@@ -42,18 +42,18 @@ function encodeBodyWithEncoding(
4242
}
4343
if (encoding === ContentEncoding.Brotli) {
4444
const enc = zlib.createBrotliCompress();
45-
setFlush(enc.flush.bind(enc));
46-
return Readable.toWeb(Readable.fromWeb(body).pipe(enc));
45+
setFlush(() => enc.flush());
46+
return body.pipeThrough(Transform.toWeb(enc));
4747
}
4848
if (encoding === ContentEncoding.Gzip) {
4949
const enc = zlib.createGzip();
50-
setFlush(enc.flush.bind(enc));
51-
return Readable.toWeb(Readable.fromWeb(body).pipe(enc));
50+
setFlush(() => enc.flush());
51+
return body.pipeThrough(Transform.toWeb(enc));
5252
}
5353
if (encoding === ContentEncoding.Deflate) {
5454
const enc = zlib.createDeflate();
55-
setFlush(enc.flush.bind(enc));
56-
return Readable.toWeb(Readable.fromWeb(body).pipe(enc));
55+
setFlush(() => enc.flush());
56+
return body.pipeThrough(Transform.toWeb(enc));
5757
}
5858
return body;
5959
}

tests/compress.test.ts

Lines changed: 10 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -64,9 +64,10 @@ test('compress with asyncIterable body', async () => {
6464
const compression = ctx.get(CompressionKey.Consumer);
6565
const body = createPushabledAsyncIterable<Uint8Array>();
6666
body.push(Uint8Array.from([1, 2, 3]));
67+
body.push(Uint8Array.from([4, 5, 6]));
6768
compression?.flush();
6869
setTimeout(() => {
69-
body.push(Uint8Array.from([4, 5, 6]));
70+
body.push(Uint8Array.from([7, 8, 9]));
7071
compression?.flush();
7172
body.end();
7273
}, 100);
@@ -83,27 +84,15 @@ test('compress with asyncIterable body', async () => {
8384
assert(res.body);
8485
const reader = res.body.getReader();
8586
const message = await reader.read();
86-
expect(message).toMatchInlineSnapshot(`
87-
{
88-
"done": false,
89-
"value": Uint8Array [
90-
1,
91-
2,
92-
3,
93-
],
94-
}
95-
`);
87+
expect(message).toEqual({
88+
done: false,
89+
value: new Uint8Array([1, 2, 3, 4, 5, 6]),
90+
});
9691
const message2 = await reader.read();
97-
expect(message2).toMatchInlineSnapshot(`
98-
{
99-
"done": false,
100-
"value": Uint8Array [
101-
4,
102-
5,
103-
6,
104-
],
105-
}
106-
`);
92+
expect(message2).toEqual({
93+
done: false,
94+
value: new Uint8Array([7, 8, 9]),
95+
});
10796

10897
await close();
10998
});

0 commit comments

Comments
 (0)