Skip to content

Commit

Permalink
fix: gun auto-reconnect
Browse files Browse the repository at this point in the history
  • Loading branch information
johackim committed May 11, 2024
1 parent 389669d commit beb2c83
Showing 1 changed file with 34 additions and 3 deletions.
37 changes: 34 additions & 3 deletions src/synchronize.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,45 @@ import { GUN_SERVER } from './constants';
import { editConfig, readConfig } from './config';

export const synchronize = () => {
const gun = Gun({ peers: [GUN_SERVER], axe: false });
const attachListeners = (gun, fn) => {
gun.get('db').get('config').on(fn);
};

gun.get('db').get('config').on(async (data) => {
const createGunInstance = () => {
const options = {
peers: [GUN_SERVER],
axe: false,
multicast: false,
radisk: false,
rfs: false,
localStorage: false,
};

return new Gun(options);
};

let gun = createGunInstance();

const sync = async (data) => {
const newConfig = typeof data === 'string' ? JSON.parse(data) : data;

if (new Date(newConfig.date) > new Date(readConfig().date)) {
editConfig({ ...newConfig, gun: false });
console.log('Synchronize...');
}
});
};

const reconnectToNewInstance = (fn) => {
gun.get('db').get('config').off();
gun = createGunInstance();

attachListeners(gun, fn);
};

attachListeners(gun, sync);

setInterval(() => {
console.log('Reconnecting...');
reconnectToNewInstance(sync);
}, 60000);
};

0 comments on commit beb2c83

Please sign in to comment.