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.
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:
However, when the internet is broken, the order is:
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 :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With