forked from pouchdb/upsert
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
99 lines (86 loc) · 2.36 KB
/
index.js
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
'use strict';
var PouchPromise;
/* istanbul ignore next */
if (typeof window !== 'undefined' && window.PouchDB) {
PouchPromise = window.PouchDB.utils.Promise;
} else {
PouchPromise = typeof global.Promise === 'function' ? global.Promise : require('lie');
}
// 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 upsertInner(db, docId, diffFun) {
if (typeof docId !== 'string') {
return PouchPromise.reject(new Error('doc id is required'));
}
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 { updated: false, rev: docRev };
}
// users aren't allowed to modify these values,
// so reset them here
newDoc._id = docId;
newDoc._rev = docRev;
return 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 */
if (err.status !== 409) {
throw err;
}
return upsertInner(db, doc._id, diffFun);
});
}
exports.upsert = function upsert(docId, diffFun, cb) {
var db = this;
var promise = upsertInner(db, docId, diffFun);
if (typeof cb !== 'function') {
return promise;
}
promise.then(function (resp) {
cb(null, resp);
}, cb);
};
exports.putIfNotExists = function putIfNotExists(docId, doc, cb) {
var db = this;
if (typeof docId !== 'string') {
cb = doc;
doc = docId;
docId = doc._id;
}
var diffFun = function (existingDoc) {
if (existingDoc._rev) {
return false; // do nothing
}
return doc;
};
var promise = upsertInner(db, docId, diffFun);
if (typeof cb !== 'function') {
return promise;
}
promise.then(function (resp) {
cb(null, resp);
}, cb);
};
/* istanbul ignore next */
if (typeof window !== 'undefined' && window.PouchDB) {
window.PouchDB.plugin(exports);
}