calvinmetcalf / crypto-pouch

plugin for encrypted pouchdb/couchdb databases
MIT License
243 stars 43 forks source link

Incoming function is applied more than once #10

Closed vpease closed 9 years ago

vpease commented 9 years ago

I am using crypto-pouch with Ionic Framework and i have noticed the incoming function (when you save some data with Put) is applied more than one time per document so the data is re encrypted. The consequence is that when i want to read with get or allDocs, the outgoing function is applied only one time and the result is data still encrypted. this is my method to add records:

 self.put = function(object){
            if (!db){
                    self.init();
                }
            db.crypto(params.getDbkey())
                .then(function(){
                db.put(object).then(function(response){
                    console.log('Insert Ok'+ JSON.stringify(response));
                }).catch(function(err){
                    db.get(object._id).then(function(response){
                        response = object;
                        return db.put(response);
                    }).then(function(response){
                        console.log('Update Ok '+ response);
                    }).catch(function(err){
                        console.log('Error al actualizar: '+err.toString());
                    });
                });
            });

Testing with a new database everytime, so all documents are inserted.

To read, i am using:

self.getAll = function(query){
            return db.crypto(params.getDbkey())
                .then(function(){
                var res =db.allDocs(query);
                return res;
            })
        };

Inserting a new document is handled in the bundle.js with the function: line 17321:

handlers.bulkDocs = function (orig, args) {
    for (var i = 0; i < args.docs.length; i++) {
      args.docs[i] = incoming(args.docs[i]);
    }
    return orig();
  }

What i have found is that after the for is completed, the line return orig() restart the function and the bucle start all over again, firing the encrypt() function in the line 19922 before saving it to the database.

calvinmetcalf commented 9 years ago

you should only be calling db.crypto(params.getDbkey()) once, so put that inside the conditional it's right bellow so it's only called when the db is created

vpease commented 9 years ago

Done. I changed my init function to this: self.init = function() { if (!db) { console.log('database is closed'); db = new window.PouchDB(dbName,{ adapter: 'websql', size: 50, auto_compaction:true}); if (!db.adapter){ db = new window.PouchDB(dbName,{ size: 50, auto_compation: true }); console.log('Usando: ' + db.adapter); } else { console.log('Usando websql'); } return db.crypto(params.getDbkey()) .then(function(){ return db; }); }; };

calvinmetcalf commented 9 years ago

tip, surround your code with a lines with ``` and it will be much more readable