all files / lib/deps/ upsert.js

100% Statements 27/27
91.67% Branches 11/12
100% Functions 7/7
100% Lines 26/26
1 statement, 1 branch Ignored     
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62                      1672× 1672× 1671×   450×   449×       1670× 1670×   1670×     735×         935× 934× 934×         934× 607×           327×   327×      
'use strict';
 
Object.defineProperty(exports, "__esModule", {
  value: true
});
 
var _promise = require('./promise');
 
var _promise2 = _interopRequireDefault(_promise);
 
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
 
// 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 _promise2.default(function (fulfill, reject) {
    db.get(docId, function (err, doc) {
      if (err) {
        /* istanbul ignore next */
        if (err.status !== 404) {
          return reject(err);
        }
        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 });
      }
 
      // users aren't allowed to modify these values,
      // so reset them here
      newDoc._id = docId;
      newDoc._rev = docRev;
      fulfill(tryAndPut(db, newDoc, diffFun));
    });
  });
}
 
function tryAndPut(db, doc, diffFun) {
  return db.put(doc).then(function (res) {
    return {
      updated: true,
      rev: res.rev
    };
  }, function (err) {
    /* istanbul ignore next */
    Iif (err.status !== 409) {
      throw err;
    }
    return upsert(db, doc._id, diffFun);
  });
}
 
exports.default = upsert;
module.exports = exports['default'];