js-waku-examples/store-js/index.html

82 lines
2.4 KiB
HTML
Raw Normal View History

2022-06-17 00:48:15 +00:00
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='UTF-8' />
<meta content='width=device-width, initial-scale=1.0' name='viewport' />
<title>JS-Waku store script tag example</title>
2022-06-17 00:48:15 +00:00
</head>
<body>
<div><h1>Timestamp of latest message seen in store</h1></div>
2022-06-17 00:48:15 +00:00
<div id='timestamp'></div>
2022-08-31 03:18:24 +00:00
<script type='module'>
import {
waitForRemotePeer,
Protocols
} from 'https://unpkg.com/js-waku@next/bundle/index.js';
import {
createWaku
} from 'https://unpkg.com/js-waku@next/bundle/lib/create_waku.js'
2022-06-17 00:48:15 +00:00
/**
* This example demonstrates how to use the js-waku minified bundle
* available on unpkg.com.
*
* It is a simple script that uses Waku Store to retrieve ping relay messages
* and displays the timestamp of the most recent ping relay message.
*/
const timestampDiv = document.getElementById('timestamp');
try {
2022-08-31 03:18:24 +00:00
timestampDiv.innerHTML = '<p>Creating waku.</p>';
const node = await createWaku({ defaultBootstrap: true });
2022-06-17 00:48:15 +00:00
timestampDiv.innerHTML = '<p>Starting waku.</p>';
2022-08-31 03:18:24 +00:00
await node.start();
2022-06-17 00:48:15 +00:00
2022-08-31 03:18:24 +00:00
timestampDiv.innerHTML = '<p>Connecting to a peer.</p>';
await waitForRemotePeer(node, [Protocols.Store]);
timestampDiv.innerHTML = '<p>Retrieving messages.</p>';
const callback = (wakuMessages) => {
// Messages are ordered with oldest first
// even with page direction `backward`
const latestFirst = wakuMessages.reverse();
const latestMessage = latestFirst[0];
if (latestMessage) {
timestampDiv.innerHTML = latestMessage.timestamp;
} else {
timestampDiv.innerHTML = '<p>No message available, go to <a href="https://js-waku.wakuconnect.dev/examples/web-chat/">web-chat</a> to send a message</p>';
2022-08-31 03:18:24 +00:00
}
2022-06-17 00:48:15 +00:00
2022-08-31 03:18:24 +00:00
// When returning true, `queryHistory` stops retrieving pages
// In our case, we only want one message, hence one page.
return true;
};
2022-06-17 00:48:15 +00:00
2022-08-31 03:18:24 +00:00
const startTime = new Date();
// Only retrieve a week of messages
startTime.setTime(Date.now() - 7 * 24 * 60 * 60 * 1000);
2022-06-17 00:48:15 +00:00
2022-08-31 03:18:24 +00:00
await node.store
.queryHistory([], {
2022-06-17 00:48:15 +00:00
callback,
pageDirection: 'backward',
pageSize: 1,
timeFilter: {
startTime,
endTime: new Date()
}
});
} catch (e) {
2022-08-31 03:18:24 +00:00
timestampDiv.innerHTML = 'Error encountered: ' + e.toString();
2022-06-17 00:48:15 +00:00
}
</script>
</body>
</html>