Updates
This commit is contained in:
@@ -0,0 +1,56 @@
|
||||
/**
|
||||
* Basic usage example for hyper-p2p-reactive-state
|
||||
* Run with: bare examples/basic-usage.js
|
||||
*/
|
||||
|
||||
const process = require('bare-process')
|
||||
const { HyperP2PReactiveState } = require('../index.js')
|
||||
|
||||
async function main () {
|
||||
const topic = 'example-reactive-state-' + Date.now()
|
||||
|
||||
const state = new HyperP2PReactiveState({
|
||||
topic,
|
||||
metadata: { role: 'example', version: '0.1.0' }
|
||||
})
|
||||
|
||||
state.on('ready', () => console.log('✅ State manager ready'))
|
||||
state.on('change', (change) => {
|
||||
console.log(`🔄 Change: ${change.key} = ${JSON.stringify(change.value)} (by ${change.peer})`)
|
||||
})
|
||||
state.on('peer-connected', (p) => console.log('👥 Peer connected:', p.peer))
|
||||
|
||||
await state.ready()
|
||||
|
||||
// Set some reactive state
|
||||
await state.set('game:score', 1250)
|
||||
await state.set('game:player', { name: 'Agent', xp: 3400 })
|
||||
await state.set('config:theme', 'cyberpunk')
|
||||
|
||||
console.log('Current state:', state.toJSON())
|
||||
|
||||
// Query example
|
||||
const gameKeys = state.query({ keyPrefix: 'game:' })
|
||||
console.log('Game related:', gameKeys.length, 'entries')
|
||||
|
||||
// Subscribe example
|
||||
const unsub = state.subscribe(['config:theme', 'game:score'], (c) => {
|
||||
console.log('📡 Subscribed update:', c)
|
||||
})
|
||||
|
||||
await state.set('config:theme', 'neon')
|
||||
await state.delete('game:score')
|
||||
|
||||
unsub()
|
||||
|
||||
console.log('Peers:', state.getPeers().length)
|
||||
|
||||
// Simulate shutdown
|
||||
setTimeout(async () => {
|
||||
await state.close()
|
||||
console.log('✅ Closed gracefully')
|
||||
process.exit(0)
|
||||
}, 2000)
|
||||
}
|
||||
|
||||
main().catch(console.error)
|
||||
Reference in New Issue
Block a user