Search code examples
ionic-frameworksynchronizationpouchdbdestroy

PouchDB: is a destroy clean while doing live replication?


I am having data corruption in my mobile app (Ionic 1), in very occasional cases.

The app is working with users logging to a remote CouchDB server. Each user has its own db in the server. There is only one session at a time in the app, but it may happen that user A uses the app, logs out, then user B logs in to use the app.

Locally, the app has one unique PouchDB, which is created on login, then live-synchronized with the user's remote couchDB, then destroyed on logout.

Problem: in very random and unfrequent cases that I cannot reproduce, some data of user A appear in the data of user B! and more over, some data of user A are destroyed (maybe transferred to B, not sure).

So, I was wondering what happens if I call PouchDB.destroy while a live sync is running (PouchDB.replicate with options { live: true, retry:true, continuous:true } in both ways: local to remote and remote to local). Is destroy doing something to cleanly stop the replication? If not, it might explain that some data are transferred from old-local A database to new-local B database (I have tried to browse the PouchDB source code but got lost in it. I could just see that Replication.cancel is called from its onDestroy method, but not sure it handles things right for my case).

Many thanks for any help!


Solution

  • The safest way to destroy a database during replication is to first call cancel() and then wait for the complete event. For instance:

    var sync = db.sync(otherDB, {live: true, retry: true});
    sync.on('complete', function () {
      db.destroy().then(/* ... */);
    });
    /* ... */
    sync.cancel(); // will trigger a 'complete'

    Hope that helps!