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

83 lines
2.5 KiB
HTML
Raw Normal View History

2021-10-12 03:13:54 +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 unpkg example</title>
</head>
<body>
<div><h1>Timestamp of latest relay ping</h1></div>
<div id='timestamp'></div>
<script
src='https://unpkg.com/js-waku@latest/build/umd/js-waku.min.bundle.js'></script>
2021-10-12 03:13:54 +00:00
<script>
/**
* This example demonstrates how to use the js-waku minified bundle
* available on unpkg.com.
*
2022-02-11 05:46:41 +00:00
* It is a simple script that uses Waku Store to retrieve ping relay messages
2021-10-12 03:13:54 +00:00
* and displays the timestamp of the most recent ping relay message.
*/
const timestampDiv = document.getElementById('timestamp');
try {
timestampDiv.innerHTML = '<p>Starting waku.</p>';
2022-02-11 05:46:41 +00:00
jswaku.Waku.create({ bootstrap: { default: true } }).catch(e => {
2021-10-12 03:13:54 +00:00
timestampDiv.innerHTML = 'Failed to create Waku: ' + e.toString();
}
).then(waku => {
timestampDiv.innerHTML = '<p>Connecting to a peer.</p>';
2022-02-11 05:46:41 +00:00
waku.waitForRemotePeer()
2021-10-12 03:13:54 +00:00
.catch((e) => {
timestampDiv.innerHTML = 'Failed to connect to peers' + e.toString();
})
.then(() => {
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 ping message available</p>';
}
// When returning true, `queryHistory` stops retrieving pages
// In our case, we only want one message, hence one page.
return true;
};
const startTime = new Date();
// Only retrieve a week of messages
startTime.setTime(Date.now() - 7 * 24 * 60 * 60 * 1000);
waku.store
.queryHistory(['/relay-ping/1/ping/null'], {
callback,
pageDirection: 'backward',
pageSize: 1,
timeFilter: {
startTime,
endTime: new Date()
}
})
.catch((e) => {
timestampDiv.innerHTML = 'Failed to retrieve messages' + e.toString();
});
});
});
} catch (e) {
timestampDiv.innerHTML = 'Failed to start application' + e.toString();
}
</script>
</body>
</html>