diff --git a/README.md b/README.md index 97af1a4..c332f52 100644 --- a/README.md +++ b/README.md @@ -218,6 +218,31 @@ The value for `documentType` is the camelCase version of the primary model name. For best results, only create/update records using the full model definition. Treat the others as read-only. +## Multiple databases for the same model + +In some cases it might diserable (security related, where you want a given user to only have some informations stored on his computer) to have multiple databases for the same model of data. + +`Ember-Pouch` allows you to dynamically change the database a model is using by calling the function `changeDb` on the adapter. + +```javascript +function changeProjectDatabase(dbName, dbUser, dbPassword) { + // CouchDB is serving at http://localhost:5455 + let remote = new PouchDB('http://localhost:5455/' + dbName); + // here we are using pouchdb-authentication for credential supports + remote.login( dbUser, dbPassword).then( + function (user) { + let db = new PouchDB(dbName) + db.sync(remote, {live:true, retry:true}) + // grab the adapter, it can be any ember-pouch adapter. + let adapter = this.store.adapterFor('project'); + // this is where we told the adapter to change the current database. + adapter.changeDb(db); + } + ) +} +``` + + ## Installation * `git clone` this repository diff --git a/addon/adapters/pouch.js b/addon/adapters/pouch.js index 281157f..0712346 100644 --- a/addon/adapters/pouch.js +++ b/addon/adapters/pouch.js @@ -25,15 +25,35 @@ export default DS.RESTAdapter.extend({ // reloading redundant. shouldReloadRecord: function () { return false; }, shouldBackgroundReloadRecord: function () { return false; }, - - _startChangesToStoreListener: on('init', function () { - this.changes = this.get('db').changes({ - since: 'now', - live: true, - returnDocs: false - }).on('change', bind(this, 'onChange')); + _onInit : on('init', function() { + this._startChangesToStoreListener(); }), + _startChangesToStoreListener: function () { + var db = this.get('db'); + if (db) { + this.changes = db.changes({ + since: 'now', + live: true, + returnDocs: false + }).on('change', bind(this, 'onChange')); + } + }, + changeDb: function(db) { + if (this.changes) { + this.changes.cancel(); + } + var store = this.store; + var schema = this._schema || []; + + for (var i = 0, len = schema.length; i < len; i++) { + store.unloadAll(schema[i].singular); + } + + this._schema = null; + this.set('db', db); + this._startChangesToStoreListener(); + }, onChange: function (change) { // If relational_pouch isn't initialized yet, there can't be any records // in the store to update.