2021-03-10 16:22:49 +11:00
|
|
|
// Ensure that this class matches the proto interface while
|
2021-03-22 15:34:13 +11:00
|
|
|
import { Reader } from 'protobufjs/minimal';
|
2021-03-10 16:22:49 +11:00
|
|
|
|
2021-03-22 15:34:13 +11:00
|
|
|
// Protecting the user from protobuf oddities
|
|
|
|
|
import { WakuMessage } from '../proto/waku/v2/waku';
|
2021-03-10 16:22:49 +11:00
|
|
|
|
2021-03-22 15:34:13 +11:00
|
|
|
const DEFAULT_CONTENT_TOPIC = 1;
|
|
|
|
|
const DEFAULT_VERSION = 0;
|
2021-03-10 16:22:49 +11:00
|
|
|
|
2021-03-22 15:34:13 +11:00
|
|
|
export class Message {
|
|
|
|
|
private constructor(
|
|
|
|
|
public payload?: Uint8Array,
|
|
|
|
|
public contentTopic?: number,
|
|
|
|
|
public version?: number
|
|
|
|
|
) {}
|
2021-03-10 16:22:49 +11:00
|
|
|
|
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-22 15:34:13 +11:00
|
|
|
const payload = Buffer.from(message, 'utf-8');
|
|
|
|
|
return new Message(payload, DEFAULT_CONTENT_TOPIC, DEFAULT_VERSION);
|
2021-03-10 16:22:49 +11:00
|
|
|
}
|
|
|
|
|
|
2021-03-22 15:34:13 +11:00
|
|
|
static fromBinary(bytes: Uint8Array): Message {
|
|
|
|
|
const wakuMsg = WakuMessage.decode(Reader.create(bytes));
|
|
|
|
|
return new Message(wakuMsg.payload, wakuMsg.contentTopic, wakuMsg.version);
|
2021-03-10 16:22:49 +11:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
toBinary(): Uint8Array {
|
2021-03-22 15:34:13 +11:00
|
|
|
return WakuMessage.encode({
|
|
|
|
|
payload: this.payload,
|
|
|
|
|
version: this.version,
|
|
|
|
|
contentTopic: this.contentTopic,
|
|
|
|
|
}).finish();
|
2021-03-10 16:22:49 +11:00
|
|
|
}
|
|
|
|
|
|
2021-03-24 16:31:54 +11:00
|
|
|
utf8Payload(): string {
|
|
|
|
|
if (!this.payload) {
|
|
|
|
|
return '';
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return Array.from(this.payload)
|
|
|
|
|
.map((char) => {
|
|
|
|
|
return String.fromCharCode(char);
|
|
|
|
|
})
|
|
|
|
|
.join('');
|
|
|
|
|
}
|
|
|
|
|
|
2021-03-10 16:22:49 +11:00
|
|
|
// 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.
|
2021-03-10 16:22:49 +11:00
|
|
|
isEqualTo(other: Message) {
|
2021-03-22 15:34:13 +11:00
|
|
|
const payloadsAreEqual =
|
|
|
|
|
this.payload && other.payload
|
|
|
|
|
? Buffer.compare(this.payload, other.payload) === 0
|
|
|
|
|
: !(this.payload || other.payload);
|
2021-03-10 16:22:49 +11:00
|
|
|
return (
|
2021-03-22 15:34:13 +11:00
|
|
|
payloadsAreEqual &&
|
2021-03-10 16:22:49 +11:00
|
|
|
this.contentTopic === other.contentTopic &&
|
|
|
|
|
this.version === other.version
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
}
|