-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathupsert.js
More file actions
41 lines (37 loc) · 1.1 KB
/
Copy pathupsert.js
File metadata and controls
41 lines (37 loc) · 1.1 KB
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
'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'));
}
db.get(docId, function (err, doc) {
if (err) {
if (err.name !== 'not_found') {
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.name !== 'conflict') {
throw err;
}
return upsert(db, doc, diffFun);
});
}
module.exports = upsert;