Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to know when we've lost sync with a remote CouchDB

I have a mobile app using PouchDB that listens for changes from a remote CouchDB server. Occasionally the app pushes it's own changes up. Is there a way to check to see if I still have an active "connection" to the remote CouchDB instance?

The best solution I can come up with so far is to periodically call db.info and see if I get an error back, but that seems slightly risky.

like image 348
captain_jim1 Avatar asked Nov 12 '14 17:11

captain_jim1


1 Answers

As far as I could find out, PouchDB has no event to inform us that the syncing was stopped because of a disruption in the internet connection. I did a small hack to solve this.

When the sync is happening properly, and you make a change to your local PouchDB, the order in which events are fired is:

  1. active
  2. change
  3. paused

However, when the internet is broken, the order is:

  1. active
  2. paused

There is no change event fired when syncing with the remote DB isn't taking place.

So, what I've done is made two flags for the active and change events , pouchDbSyncActiveEvent and pouchDbSyncChangeEvent respectively, and initialized both as false. Turn pouchDbSyncActiveEvent to true in the callback for the 'active' event. This will run regardless of whether there is internet or not. Turn pouchDbSyncChangeEvent to true in the callback for the 'change' event. If there is no internet, this won't run and pouchDbSyncChangeEvent will still remain false, and the 'paused' event will be fired soon after. This informs us that the syncing was stopped.

Code:

let pouchDbSyncActiveEvent = false
let pouchDbSyncChangeEvent = false

localPouchDb.sync(remoteCouchDb, {
  live: true,
  retry: true
})
.on('active', (change) => {

  pouchDbSyncActiveEvent = true

})
.on('change', (change) => {

  pouchDbSyncChangeEvent = true

})
.on('paused', (info) => {

  if(pouchDbSyncActiveEvent == true && pouchDbSyncChangeEvent == false){

    // Gotcha! Syncing with remote DB not happening!

  }
  else {

    // Everything's ok. Syncing with remote DB happening normally.

  }

  pouchDbSyncActiveEvent = false
  pouchDbSyncChangeEvent = false

})

Note: You can write the .on event listener methods in the order you wish, but it is good to write them in the order they are executed :)

like image 164
Nikhil Sinha Avatar answered Dec 28 '22 20:12

Nikhil Sinha