orbit-db/examples/keyvalue.js
2017-11-28 12:30:40 +01:00

67 lines
1.5 KiB
JavaScript

'use strict'
const IPFS = require('ipfs')
const OrbitDB = require('../src/OrbitDB')
const userId = 1
const creatures = ['🐙', '🐬', '🐋', '🐠', '🐡', '🦀', '🐢', '🐟', '🐳']
const output = (user) => {
if (!user)
return
let output = ``
output += `----------------------\n`
output += `User\n`
output += `----------------------\n`
output += `Id: ${userId}\n`
output += `Avatar: ${user.avatar}\n`
output += `Updated: ${user.updated}\n`
output += `----------------------\n`
console.log(output)
}
console.log("Starting...")
const ipfs = new IPFS({
repo: './orbitdb/examples/ipfs',
start: true,
EXPERIMENTAL: {
pubsub: true,
},
})
ipfs.on('error', (err) => console.error(err))
ipfs.on('ready', async () => {
let db
try {
const orbitdb = new OrbitDB(ipfs, './orbitdb/examples/eventlog')
db = await orbitdb.kvstore('example', { overwrite: true })
await db.load()
// Query immediately after loading
const user = db.get(userId)
output(user)
} catch (e) {
console.error(e)
process.exit(1)
}
const query = async () => {
// Randomly select an avatar
const index = Math.floor(Math.random() * creatures.length)
// Set the key to the newly selected avatar and update the timestamp
await db.put(userId, { avatar: creatures[index], updated: new Date().getTime() })
// Get the value of the key
const user = db.get(userId)
// Display the value
output(user)
}
console.log("Starting update loop...")
setInterval(query, 1000)
})