-
Notifications
You must be signed in to change notification settings - Fork 592
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
chore: add compression utilities for browser
- Loading branch information
Showing
2 changed files
with
40 additions
and
0 deletions.
There are no files selected for viewing
2 changes: 2 additions & 0 deletions
2
packages/middleware-compression/src/compressStream.browser.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,2 @@ | ||
export const compressStream = async (body: ReadableStream): Promise<ReadableStream> => | ||
body.pipeThrough(new CompressionStream("gzip")); |
38 changes: 38 additions & 0 deletions
38
packages/middleware-compression/src/compressString.browser.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,38 @@ | ||
import { toUint8Array } from "@smithy/util-utf8"; | ||
|
||
import { compressStream } from "./compressStream.browser"; | ||
import { CompressionAlgorithm } from "./constants"; | ||
|
||
export const compressString = async (body: any, algorithm: CompressionAlgorithm): Promise<Uint8Array> => { | ||
// Only gzip shall be supported initial release. | ||
if (algorithm !== CompressionAlgorithm.GZIP) { | ||
throw new Error(`Only '${CompressionAlgorithm.GZIP}' is supported for compression. Got '${algorithm}'.`); | ||
} | ||
|
||
const inputUint8Array = toUint8Array(body); | ||
const inputStream = new ReadableStream({ | ||
start(controller) { | ||
controller.enqueue(inputUint8Array); | ||
controller.close(); | ||
}, | ||
}); | ||
|
||
const outputStream = await compressStream(inputStream); | ||
|
||
const reader = outputStream.getReader(); | ||
const chunks: Uint8Array[] = []; | ||
while (true) { | ||
const { done, value } = await reader.read(); | ||
if (done) { | ||
break; | ||
} | ||
chunks.push(value); | ||
} | ||
|
||
return new Uint8Array( | ||
chunks.reduce((acc, chunk) => { | ||
acc.push(...chunk); | ||
return acc; | ||
}, []) | ||
); | ||
}; |