Last active
July 4, 2017 14:02
-
-
Save roydejong/47356ed12f2676737cdf968614578922 to your computer and use it in GitHub Desktop.
PouchDB: Add or update record (sync / merge)
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
static addOrUpdate(id, document) { | |
return new Promise(function (resolve, reject) { | |
let doStore = function (originalDocument) { | |
// Merge the document: First, set the ID. Then apply the existing doc on top if possible. Finally, apply the changed doc. | |
let mergedDoc = { | |
_id: id | |
}; | |
if (originalDocument) { | |
for (let key in originalDocument) { | |
mergedDoc[key] = originalDocument[key]; | |
} | |
} | |
for (let key in newDocument) { | |
mergedDoc[key] = newDocument[key]; | |
} | |
// Verify whether the merged document actually has any changed properties other than revision | |
if (originalDocument) { | |
let anyUnequal = false; | |
for (let key in mergedDoc) { | |
if (key === "_rev") { | |
continue; | |
} | |
if (originalDocument[key] !== mergedDoc[key]) { | |
console.log('PROP NOT EQUAL', key); | |
anyUnequal = true; | |
break; | |
} | |
} | |
if (!anyUnequal) { | |
// All properties equal, no need to perform merge | |
resolve(mergedDoc); | |
return; | |
} | |
} | |
// Update needed, perform put | |
DeviceDb.db.put(mergedDoc).then(function (response) { | |
mergedDoc._rev = response.rev; | |
resolve(mergedDoc); | |
}) | |
.catch(function (err) { | |
reject(err); | |
}); | |
}; | |
// Fetch the document, see what happens, then store or update | |
db.get(id).then(function (getDoc) { | |
// Document exists, update | |
doStore(getDoc); | |
}).catch(function (err) { | |
if (err.status === 404) { | |
// Document does not exist, create | |
doStore(null); | |
} else { | |
// Something else went wrong, general failure | |
reject(err); | |
} | |
}); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example use:
And again:
Also, it won't create a new revision if nothing changed.