Skip to content

Commit

Permalink
catch errors thrown in diff function
Browse files Browse the repository at this point in the history
  • Loading branch information
tyler-johnson authored and nolanlawson committed Nov 22, 2015
1 parent e9e8b43 commit c5848b0
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 27 deletions.
50 changes: 23 additions & 27 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,36 +12,32 @@ if (typeof window !== 'undefined' && window.PouchDB) {
// 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 upsertInner(db, docId, diffFun) {
return new PouchPromise(function (fulfill, reject) {
if (typeof docId !== 'string') {
return reject(new Error('doc id is required'));
}

db.get(docId, function (err, doc) {
if (err) {
/* istanbul ignore next */
if (err.status !== 404) {
return reject(err);
}
doc = {};
}
if (typeof docId !== 'string') {
return PouchPromise.reject(new Error('doc id is required'));
}

// the user might change the _rev, so save it for posterity
var docRev = doc._rev;
var newDoc = diffFun(doc);
return db.get(docId).catch(function (err) {
/* istanbul ignore next */
if (err.status !== 404) {
throw err;
}
return {};
}).then(function (doc) {
// the user might change the _rev, so save it for posterity
var docRev = doc._rev;
var newDoc = diffFun(doc);

if (!newDoc) {
// if the diffFun returns falsy, we short-circuit as
// an optimization
return fulfill({updated: false, rev: docRev});
}
if (!newDoc) {
// if the diffFun returns falsy, we short-circuit as
// an optimization
return { updated: false, rev: docRev };
}

// users aren't allowed to modify these values,
// so reset them here
newDoc._id = docId;
newDoc._rev = docRev;
fulfill(tryAndPut(db, newDoc, diffFun));
});
// users aren't allowed to modify these values,
// so reset them here
newDoc._id = docId;
newDoc._rev = docRev;
return tryAndPut(db, newDoc, diffFun);
});
}

Expand Down
10 changes: 10 additions & 0 deletions test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -373,5 +373,15 @@ function tests(dbName, dbType) {
});
});

it('errors thrown in diff function shouldn\'t crash the system', function () {
return db.upsert('foo', function () {
throw new Error("An upsert diff error.");
}).then(function () {
throw new Error("Finished upsert without throwing error.");
}, function (e) {
should.exist(e);
});
});

});
}

0 comments on commit c5848b0

Please sign in to comment.