-
Notifications
You must be signed in to change notification settings - Fork 12
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
(pouchdb/pouchdb#3410) - use pouchdb-upsert
- Loading branch information
1 parent
82ed33f
commit 1f67e2f
Showing
3 changed files
with
6 additions
and
39 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,41 +1,7 @@ | ||
'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')); | ||
} | ||
var upsert = require('pouchdb-upsert').upsert; | ||
|
||
db.get(docId, function (err, doc) { | ||
if (err) { | ||
if (err.status !== 404) { | ||
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.status !== 409) { | ||
throw err; | ||
} | ||
return upsert(db, doc, diffFun); | ||
}); | ||
} | ||
|
||
module.exports = upsert; | ||
module.exports = function (db, doc, diffFun) { | ||
return upsert.apply(db, [doc, diffFun]); | ||
}; |