Skip to content

Commit

Permalink
Update event stream payload encoding function
Browse files Browse the repository at this point in the history
  • Loading branch information
Bret Ambrose committed Aug 29, 2024
1 parent e0a7c07 commit 8f3e367
Show file tree
Hide file tree
Showing 4 changed files with 50 additions and 5 deletions.
37 changes: 37 additions & 0 deletions lib/eventstream_rpc_utils.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/

import * as eventstream_rpc_utils from "./eventstream_rpc_utils";

jest.setTimeout(5000);

test('Encode string payload as base64', async () => {
let encodedPayload = eventstream_rpc_utils.encodePayloadAsString("HelloWorld");
expect(encodedPayload).toEqual("SGVsbG9Xb3JsZA==");
});

test('Encode ArrayBuffer payload as base64', async () => {
let buffer = new ArrayBuffer(10);
let writeView = new Uint8Array(buffer);
for (let i = 0; i < 10; i++) {
writeView[i] = 65;
}

let encodedPayload = eventstream_rpc_utils.encodePayloadAsString(buffer);
expect(encodedPayload).toEqual("QUFBQUFBQUFBQQ==");
});

test('Encode view payload as base64', async () => {
let buffer = new ArrayBuffer(10);
let writeView = new Uint8Array(buffer);
for (let i = 0; i < 10; i++) {
writeView[i] = 65;
}

let view = new DataView(buffer, 1, 8);

let encodedPayload = eventstream_rpc_utils.encodePayloadAsString(view);
expect(encodedPayload).toEqual("QUFBQUFBQUE=");
});
10 changes: 9 additions & 1 deletion lib/eventstream_rpc_utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,15 @@ import {CrtError, eventstream} from "aws-crt";
* @return a base64-encoded string
*/
export function encodePayloadAsString(payload : eventstream.Payload) : string {
return Buffer.from(payload).toString("base64");
if (ArrayBuffer.isView(payload)) {
return Buffer.from(payload.buffer, payload.byteOffset, payload.byteLength).toString("base64");
} else if (typeof payload === "string") {
let value = payload as string;
return Buffer.from(value).toString("base64");
} else {
let value = payload as ArrayBuffer;
return Buffer.from(value).toString("base64");
}
}

/**
Expand Down
6 changes: 3 additions & 3 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@
},
"devDependencies": {
"@types/jest": "^27.0.1",
"@types/node": "^10.17.54",
"@types/node": "^14.18.63",
"@types/puppeteer": "^5.4.7",
"@types/ws": "8.5.4",
"cmake-js": "^7.3.0",
Expand Down

0 comments on commit 8f3e367

Please sign in to comment.