forked from carpetsage/egg
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathencode.ts
27 lines (25 loc) · 813 Bytes
/
encode.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import { ProtobufType } from './types';
import { uint8ArrayToBinaryString } from './utils';
/**
* Encode message object as base64-encoded protobuf.
* @param message - Message type, e.g. ei.ContractCoopStatusRequest.
* @param messageObj - Plain object of payload to be encoded.
* @param authenticated - Whether to encode as AuthenticatedMessage.
* @returns
* @throws Throws on encoding failure.
*/
export function encodeMessage(
message: ProtobufType,
messageObj: unknown,
authenticated = false
): string {
if (authenticated) {
throw new Error(`Authenticated encoding not implemented.`);
}
try {
const buf = message.encode(messageObj).finish();
return btoa(uint8ArrayToBinaryString(buf));
} catch (e) {
throw new Error(`Encoding ${JSON.stringify(messageObj)}: ${e}.`);
}
}