(db, docId, diffFun)
| 725 | // the diffFun tells us what delta to apply to the doc. it either returns |
| 726 | // the doc, or false if it doesn't need to do an update after all |
| 727 | function upsert(db, docId, diffFun) { |
| 728 | return db.get(docId) |
| 729 | .catch(function (err) { |
| 730 | /* istanbul ignore next */ |
| 731 | if (err.status !== 404) { |
| 732 | throw err; |
| 733 | } |
| 734 | return {}; |
| 735 | }) |
| 736 | .then(function (doc) { |
| 737 | // the user might change the _rev, so save it for posterity |
| 738 | var docRev = doc._rev; |
| 739 | var newDoc = diffFun(doc); |
| 740 | |
| 741 | if (!newDoc) { |
| 742 | // if the diffFun returns falsy, we short-circuit as |
| 743 | // an optimization |
| 744 | return {updated: false, rev: docRev}; |
| 745 | } |
| 746 | |
| 747 | // users aren't allowed to modify these values, |
| 748 | // so reset them here |
| 749 | newDoc._id = docId; |
| 750 | newDoc._rev = docRev; |
| 751 | return tryAndPut(db, newDoc, diffFun); |
| 752 | }); |
| 753 | } |
| 754 | |
| 755 | function tryAndPut(db, doc, diffFun) { |
| 756 | return db.put(doc).then(function (res) { |
no test coverage detected
searching dependent graphs…