Skip to content

Commit

Permalink
feat(store): live sync store records on connection to every peer
Browse files Browse the repository at this point in the history
  • Loading branch information
DEgITx committed Jun 18, 2018
1 parent 9365219 commit 9c7379e
Showing 1 changed file with 19 additions and 9 deletions.
28 changes: 19 additions & 9 deletions src/background/store.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,10 @@ module.exports = class P2PStore extends EventEmitter {
{
super()
this.id = 0
Object.defineProperty(p2p.info, 'store', {
enumerable: true,
get: () => this.id
});
this.synchronized = false

console.log('connect p2p store...')
Expand All @@ -22,12 +26,14 @@ module.exports = class P2PStore extends EventEmitter {

console.log('store db index', this.id)

let lock = false
this.p2p.events.on('peer', () => {
if(lock)
return
lock = true
setTimeout(() => this.sync(), 1000)
this.p2p.events.on('peer', (peer) => {
if(peer.info && peer.info.store)
{
if(peer.info.store > this.id)
this.sync(peer) // sync db
else if(peer.info.store === this.id)
this.synchronized = true
}
})
})

Expand Down Expand Up @@ -69,9 +75,9 @@ module.exports = class P2PStore extends EventEmitter {
})
}

sync()
sync(peer)
{
console.log('sync db on version', this.id)
console.log('sync db on version', this.id, peer ? `from peer ${peer.peerId}` : '')
const processSync = (data, nil, peer) => {
if(!data || !data.records)
return
Expand All @@ -88,7 +94,11 @@ module.exports = class P2PStore extends EventEmitter {
peer.emit('dbSync', {id: this.id}, processSync)
}
}
this.p2p.emit('dbSync', {id: this.id}, processSync)
if(peer)
peer.emit('dbSync', {id: this.id}, processSync)
else
this.p2p.emit('dbSync', {id: this.id}, processSync)

this.synchronized = true
}

Expand Down

0 comments on commit 9c7379e

Please sign in to comment.