Created
May 17, 2020 15:25
-
-
Save ericlowry/ce729dfdcc3d353344a554acefc434ae to your computer and use it in GitHub Desktop.
couchdb nano upsert that preserves mdate and muser (slower than upsert which uses HEAD for _rev)
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
// | |
// async upsert( db, doc[, id] ) | |
// | |
// attempts to insert a document, on document conflict, attempt to create a new version | |
// | |
const upsert = (db, doc, id) => | |
// attempt to insert the doucment "as is" | |
db.insert(doc, id).catch(err => { | |
// for anything other than a document conflict... | |
if (err.statusCode !== 409) | |
// ...re-throw the error. | |
throw err; | |
// get the document id from the parameter or the document itself | |
const _id = id || doc._id; | |
// grab the old document | |
return db.get(_id) | |
.then(({ _rev, cdate, cuser }) => { | |
doc._id = _id; | |
doc._rev = _rev; | |
doc.cdate = cdate; | |
doc.cuser = cuser; | |
return db.insert(doc); | |
}) | |
.catch(err => { | |
throw err; // unexpected error from db.head() | |
}); | |
}); | |
module.exports = upsert; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment