Skip to content

Commit

Permalink
chore: add compression utilities for browser
Browse files Browse the repository at this point in the history
  • Loading branch information
trivikr committed Dec 28, 2023
1 parent 92b81f8 commit 15402f6
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 0 deletions.
2 changes: 2 additions & 0 deletions packages/middleware-compression/src/compressStream.browser.ts
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 packages/middleware-compression/src/compressString.browser.ts
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;
}, [])
);
};

0 comments on commit 15402f6

Please sign in to comment.