js-waku/examples/web-chat/src/chat_message.ts

66 lines
1.6 KiB
TypeScript
Raw Normal View History

2022-02-04 14:12:00 +11:00
import { Reader } from "protobufjs/minimal";
2022-02-04 14:12:00 +11:00
import * as proto from "./proto/chat_message";
2021-05-10 15:53:05 +10:00
/**
* 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 {
const timestampNumber = Math.floor(timestamp.valueOf() / 1000);
2022-02-04 14:12:00 +11:00
const payload = Buffer.from(text, "utf-8");
return new ChatMessage({
timestamp: timestampNumber,
nick,
payload,
});
}
2021-05-10 15:53:05 +10:00
/**
* Decode a protobuf payload to a ChatMessage.
* @param bytes The payload to decode.
*/
static decode(bytes: Uint8Array): ChatMessage {
const protoMsg = proto.ChatMessage.decode(Reader.create(bytes));
return new ChatMessage(protoMsg);
}
2021-05-10 15:53:05 +10:00
/**
* Encode this ChatMessage to a byte array, to be used as a protobuf payload.
* @returns The encoded payload.
*/
encode(): Uint8Array {
return proto.ChatMessage.encode(this.proto).finish();
}
get timestamp(): Date {
return new Date(this.proto.timestamp * 1000);
}
get nick(): string {
return this.proto.nick;
}
get payloadAsUtf8(): string {
if (!this.proto.payload) {
2022-02-04 14:12:00 +11:00
return "";
}
2022-02-04 14:12:00 +11:00
return Buffer.from(this.proto.payload).toString("utf-8");
}
}