2021-03-10 14:24:23 +11:00
|
|
|
import { TextDecoder, TextEncoder } from 'util';
|
|
|
|
|
|
|
|
import test from 'ava';
|
2021-03-10 14:55:16 +11:00
|
|
|
import Pubsub from 'libp2p-interfaces/src/pubsub';
|
2021-03-10 14:24:23 +11:00
|
|
|
|
|
|
|
import { createNode } from './node';
|
2021-03-10 15:08:27 +11:00
|
|
|
import { CODEC } from './waku_relay';
|
2021-03-10 14:24:23 +11:00
|
|
|
|
2021-03-10 14:30:31 +11:00
|
|
|
function delay(ms: number) {
|
|
|
|
return new Promise((resolve) => setTimeout(resolve, ms));
|
2021-03-10 14:24:23 +11:00
|
|
|
}
|
|
|
|
|
|
|
|
test('Can publish message', async (t) => {
|
2021-03-10 14:30:31 +11:00
|
|
|
const topic = 'news';
|
2021-03-10 14:55:16 +11:00
|
|
|
const message = 'Bird bird bird, bird is the word!';
|
2021-03-10 14:24:23 +11:00
|
|
|
|
2021-03-10 14:30:31 +11:00
|
|
|
const [node1, node2] = await Promise.all([createNode(), createNode()]);
|
2021-03-10 14:24:23 +11:00
|
|
|
|
|
|
|
// Add node's 2 data to the PeerStore
|
2021-03-10 14:30:31 +11:00
|
|
|
node1.peerStore.addressBook.set(node2.peerId, node2.multiaddrs);
|
|
|
|
await node1.dial(node2.peerId);
|
|
|
|
await node1.pubsub.subscribe(topic);
|
|
|
|
await node2.pubsub.subscribe(topic);
|
2021-03-10 14:24:23 +11:00
|
|
|
|
2021-03-10 14:55:16 +11:00
|
|
|
// Setup the promise before publishing to ensure the event is not missed
|
|
|
|
// TODO: Is it possible to import `Message` type?
|
2021-03-10 14:56:12 +11:00
|
|
|
const promise = waitForNextData(node1.pubsub, topic);
|
2021-03-10 14:24:23 +11:00
|
|
|
|
2021-03-10 14:55:16 +11:00
|
|
|
await delay(500);
|
2021-03-10 14:24:23 +11:00
|
|
|
|
2021-03-10 14:30:31 +11:00
|
|
|
await node2.pubsub.publish(topic, new TextEncoder().encode(message));
|
2021-03-10 14:24:23 +11:00
|
|
|
|
2021-03-10 14:55:16 +11:00
|
|
|
const node1Received = await promise;
|
2021-03-10 14:24:23 +11:00
|
|
|
|
2021-03-10 14:30:31 +11:00
|
|
|
t.deepEqual(node1Received, message);
|
2021-03-10 14:24:23 +11:00
|
|
|
});
|
2021-03-10 14:55:16 +11:00
|
|
|
|
2021-03-10 15:08:27 +11:00
|
|
|
test('Register waku relay protocol', async (t) => {
|
|
|
|
const node = await createNode();
|
|
|
|
|
|
|
|
const protocols = Array.from(node.upgrader.protocols.keys());
|
|
|
|
|
|
|
|
t.truthy(protocols.findIndex((value) => value == CODEC));
|
|
|
|
});
|
|
|
|
|
2021-03-10 14:55:16 +11:00
|
|
|
function waitForNextData(pubsub: Pubsub, topic: string) {
|
|
|
|
return new Promise((resolve) => {
|
|
|
|
pubsub.once(topic, resolve);
|
2021-03-10 14:56:12 +11:00
|
|
|
}).then((msg: any) => {
|
|
|
|
return new TextDecoder().decode(msg.data);
|
2021-03-10 14:55:16 +11:00
|
|
|
});
|
|
|
|
}
|