Search code examples
node.jschatlangun

How to sync GUN db when new peer connects


I have set up a simple node.js app as a proof of concept, where I want peers on a local network sync a database using gun.

I am new to gun so I am not sure if I am doing this correctly but here is my code:

var Gun = require('gun')
const address = require('network-address')
const hashToPort = require('hash-to-port')

// get username from arg eg. node index myname
const username = process.argv[2]

// create GUN server on it's own port
var server = require('http').createServer().listen(hashToPort(username))
var gun = Gun({web: server})

// listen for input from the console
process.stdin.on('data', (data) => {
    gun.get('hello').put({ word: data.toString(), user: username })
});

// Output input update
gun.get('hello').on(function(data, key) {
    console.log(data.user + ' said: ' + data.word.toString())
})

The idea is that peers can drop out and reconnect and sync to the latest version of the database.

I run the app on 2 different local network machines and it works well. The database is syncing.

If I close one app, then update the database on the open app, and then restart the 2nd app, the 2nd app does not sync with the already open app.

Is there a way to sync with the updated db when a new peer connects?

I hope that all makes sense. Please suggest if this is the wrong way to go about it.


Solution

  • @CUGreen I'm glad that the local area multicast sync is working!

    If I understand your question right, it is that you want OLD data to synced?

    1. gun.get('hello').put(data) and .on(cb) update the same object. So technically, you are syncing the whole database, you're just always getting the latest state. (Unless there is some other bug? Please let me know).
    2. What you probably want to do is .set(data) instead of .put(, this will add a NEW record to a table on hello, which you can then query all of it (old and live inserts in future) with gun.get('hello').map().on(cb)

    I do not know if this is relevant, but you may find https://gun.eco/docs/Graph-Guide a nice introduction to put/set, etc.

    And of course, if you need any assistance, there is a super friendly and active community at the http://chat.gun.eco chat room!

    If there is a bug, please report it at https://github.com/amark/gun/issues