Skip to content

Commit

Permalink
(pouchdb/pouchdb#3410) - use pouchdb-upsert
Browse files Browse the repository at this point in the history
  • Loading branch information
nolanlawson committed Jan 18, 2015
1 parent 82ed33f commit 1f67e2f
Show file tree
Hide file tree
Showing 3 changed files with 6 additions and 39 deletions.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@
"lie": "^2.6.0",
"pouchdb-collate": "^1.2.0",
"pouchdb-extend": "^0.1.0",
"pouchdb-upsert": "^1.0.2",
"spark-md5": "0.0.5"
},
"devDependencies": {
Expand Down
2 changes: 1 addition & 1 deletion test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ describe('upsert', function () {
}
}, 'foo', function () {
return false;
}).should.become('lalala');
}).should.be.fulfilled;
});
it('should error if it can\'t put', function () {
return upsert({
Expand Down
42 changes: 4 additions & 38 deletions upsert.js
Original file line number Diff line number Diff line change
@@ -1,41 +1,7 @@
'use strict';
var Promise = require('./utils').Promise;

// this is essentially the "update sugar" function from daleharvey/pouchdb#1388
// the diffFun tells us what delta to apply to the doc. it either returns
// the doc, or false if it doesn't need to do an update after all
function upsert(db, docId, diffFun) {
return new Promise(function (fulfill, reject) {
if (docId && typeof docId === 'object') {
docId = docId._id;
}
if (typeof docId !== 'string') {
return reject(new Error('doc id is required'));
}
var upsert = require('pouchdb-upsert').upsert;

db.get(docId, function (err, doc) {
if (err) {
if (err.status !== 404) {
return reject(err);
}
return fulfill(tryAndPut(db, diffFun({_id : docId}), diffFun));
}
var newDoc = diffFun(doc);
if (!newDoc) {
return fulfill(doc);
}
fulfill(tryAndPut(db, newDoc, diffFun));
});
});
}

function tryAndPut(db, doc, diffFun) {
return db.put(doc).catch(function (err) {
if (err.status !== 409) {
throw err;
}
return upsert(db, doc, diffFun);
});
}

module.exports = upsert;
module.exports = function (db, doc, diffFun) {
return upsert.apply(db, [doc, diffFun]);
};

0 comments on commit 1f67e2f

Please sign in to comment.