82 lines
2.9 KiB
HTML
82 lines
2.9 KiB
HTML
<html>
|
|
<head>
|
|
<meta charset="utf-8">
|
|
</head>
|
|
<body>
|
|
<div id="result">Loading...</div>
|
|
|
|
<script type="text/javascript" src="../../dist/orbitdb.min.js" charset="utf-8"></script>
|
|
<script type="text/javascript" src="../../node_modules/ipfs-daemon/dist/ipfs-browser-daemon.min.js" charset="utf-8"></script>
|
|
|
|
<script type="text/javascript">
|
|
|
|
const username = new Date().getTime()
|
|
const channel = 'browser-examples'
|
|
const key = 'greeting'
|
|
|
|
const elm = document.getElementById("result")
|
|
|
|
const ipfs = new IpfsDaemon()
|
|
|
|
function handleError(e) {
|
|
console.error(e.stack)
|
|
elm.innerHTML = e.message
|
|
}
|
|
|
|
ipfs.on('error', (e) => handleError(e))
|
|
|
|
ipfs.on('ready', () => {
|
|
const orbit = new OrbitDB(ipfs, username, { maxHistory: 5 })
|
|
|
|
const db = orbit.kvstore(channel)
|
|
const log = orbit.eventlog(channel + ".log")
|
|
const counter = orbit.counter(channel + ".count")
|
|
|
|
const creatures = ['👻', '🐙', '🐷', '🐬', '🐞', '🐈', '🙉', '🐸', '🐓']
|
|
|
|
let count = 1
|
|
const query = () => {
|
|
const idx = Math.floor(Math.random() * creatures.length)
|
|
const creature = creatures[idx] + " " + creatures[idx]
|
|
|
|
// Set a key-value pair
|
|
db.put(key, "db.put #" + count + " - GrEEtinGs from " + creature)
|
|
.then((res) => count ++)
|
|
.then(() => counter.inc()) // Increase the counter by one
|
|
.then(() => log.add(creature)) // Add an event to 'latest visitors' log
|
|
.then(() => {
|
|
const result = db.get(key)
|
|
const latest = log.iterator({ limit: 5 }).collect()
|
|
const count = counter.value
|
|
|
|
const output = `
|
|
<b>Key-Value Store</b>
|
|
-------------------------------------------------------
|
|
Key | Value
|
|
-------------------------------------------------------
|
|
${key} | ${result}
|
|
-------------------------------------------------------
|
|
|
|
<b>Eventlog</b>
|
|
-------------------------------------------------------
|
|
Latest Visitors
|
|
-------------------------------------------------------
|
|
${latest.reverse().map((e) => e.payload.value + " at " + new Date(e.payload.meta.ts).toISOString()).join('\n')}
|
|
|
|
<b>Counter</b>
|
|
-------------------------------------------------------
|
|
Visitor Count: ${count}
|
|
-------------------------------------------------------
|
|
`
|
|
elm.innerHTML = output.split("\n").join("<br>")
|
|
})
|
|
.catch((e) => handleError(e))
|
|
}
|
|
|
|
// Start query loop when the databse has loaded its history
|
|
db.events.on('ready', () => setInterval(query, 1000))
|
|
})
|
|
</script>
|
|
</body>
|
|
</html>
|