65 lines
1.6 KiB
TypeScript
Raw Normal View History

2022-11-18 15:46:00 +11:00
import { utf8ToBytes, bytesToUtf8 } from "@waku/byte-utils";
2022-06-17 10:48:15 +10:00
import * as proto from "./proto/chat_message";
/**
* ChatMessage is used by the various show case waku apps that demonstrates
* waku used as the network layer for chat group applications.
*
* This is included to help building PoC and MVPs. Apps that aim to be
* production ready should use a more appropriate data structure.
*/
export class ChatMessage {
public constructor(public proto: proto.ChatMessage) {}
/**
* Create Chat Message with a utf-8 string as payload.
*/
static fromUtf8String(
timestamp: Date,
nick: string,
text: string
): ChatMessage {
2022-09-01 14:30:13 +10:00
const timestampNumber = BigInt(Math.floor(timestamp.valueOf() / 1000));
2022-11-18 15:46:00 +11:00
const payload = utf8ToBytes(text);
2022-06-17 10:48:15 +10:00
return new ChatMessage({
timestamp: timestampNumber,
nick,
payload,
});
}
/**
* Decode a protobuf payload to a ChatMessage.
* @param bytes The payload to decode.
*/
static decode(bytes: Uint8Array): ChatMessage {
2022-09-01 14:30:13 +10:00
const protoMsg = proto.ChatMessage.decode(bytes);
2022-06-17 10:48:15 +10:00
return new ChatMessage(protoMsg);
}
/**
* Encode this ChatMessage to a byte array, to be used as a protobuf payload.
* @returns The encoded payload.
*/
encode(): Uint8Array {
2022-09-01 14:30:13 +10:00
return proto.ChatMessage.encode(this.proto);
2022-06-17 10:48:15 +10:00
}
get timestamp(): Date {
return new Date(Number(BigInt(this.proto.timestamp) * BigInt(1000)));
2022-06-17 10:48:15 +10:00
}
get nick(): string {
return this.proto.nick;
}
get payloadAsUtf8(): string {
if (!this.proto.payload) {
return "";
}
2022-11-18 15:46:00 +11:00
return bytesToUtf8(this.proto.payload);
2022-06-17 10:48:15 +10:00
}
}