js-waku/src/lib/waku_message.ts

72 lines
2.0 KiB
TypeScript
Raw Normal View History

2021-03-22 15:05:03 +11:00
/// <reference types="../gen/proto/waku/v2/waku_pb" />
2021-03-10 16:22:49 +11:00
import { WakuMessage } from '../gen/proto/waku/v2/waku_pb';
// Ensure that this class matches the proto interface while
// Protecting the user from protobuf oddities
export class Message {
2021-03-12 14:23:21 +11:00
public payload: Uint8Array;
2021-03-10 16:22:49 +11:00
public contentTopic: number;
public version: number;
private constructor(public protobuf: WakuMessage) {
2021-03-10 16:22:49 +11:00
this.protobuf = protobuf;
const msg = protobuf.toObject();
2021-03-12 14:23:21 +11:00
// Let's make is easier to avoid mistakes and only store in Uint8Array format
let payload;
if (typeof msg.payload === 'string') {
payload = Buffer.from(msg.payload, 'base64');
} else {
payload = msg.payload;
}
this.payload = payload;
2021-03-10 16:22:49 +11:00
this.contentTopic = msg.contentTopic;
this.version = msg.version;
}
2021-03-12 14:23:21 +11:00
/**
* Create Message from utf-8 string
* @param message
* @returns {Message}
*/
static fromUtf8String(message: string): Message {
2021-03-10 16:22:49 +11:00
const wakuMsg = new WakuMessage();
// Only Version 0 is implemented in Waku 2.
2021-03-15 15:45:41 +11:00
// 0: payload SHOULD be either plain or that encryption is done at a separate layer outside of Waku.
2021-03-10 16:22:49 +11:00
wakuMsg.setVersion(0);
// This is the content topic commonly used at this time
wakuMsg.setContentTopic(1);
2021-03-12 14:23:21 +11:00
const buf = Buffer.from(message, 'utf-8');
// Only accepts Uint8Array or base64 string
wakuMsg.setPayload(buf);
2021-03-10 16:22:49 +11:00
return new Message(wakuMsg);
}
static fromBinary(message: Uint8Array): Message {
const wakuMsg = WakuMessage.deserializeBinary(message);
return new Message(wakuMsg);
}
toBinary(): Uint8Array {
return this.protobuf.serializeBinary();
}
// Purely for tests purposes.
2021-03-12 14:23:21 +11:00
// We do consider protobuf field when checking equality
// As the content is held by the other fields.
// TODO: Consider using WakuMessage.equals
2021-03-10 16:22:49 +11:00
isEqualTo(other: Message) {
return (
2021-03-12 14:23:21 +11:00
Buffer.compare(this.payload, other.payload) === 0 &&
2021-03-10 16:22:49 +11:00
this.contentTopic === other.contentTopic &&
this.version === other.version
);
}
}