Skip to content

Instantly share code, notes, and snippets.

@nolanlawson
Created June 20, 2016 14:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nolanlawson/c9378c1402ace68a258a6ae16e10edd1 to your computer and use it in GitHub Desktop.
Save nolanlawson/c9378c1402ace68a258a6ae16e10edd1 to your computer and use it in GitHub Desktop.
conflict.js
db.changes({
since: 'now',
live: true,
include_docs: true,
conflicts: true
}).on('change', function (change) {
let doc = change.doc;
if(doc._conflicts) {
let conflicts = doc._conflicts.concat();
let promises = [doc._rev].concat(conflicts).map(function(rev){
return db.get(doc._id, {rev: rev, revs_info: true});
});
Promise.all(promises).then(function(leafs){
var ancestors = findCommonAncestors(leafs);
if(ancestors.length) {
return db.get(doc._id, {rev: ancestors[0]}).then(function(root){
return diffAndMergeDocs(leafs, root);
});
} else {
return diffAndMergeDocs(leafs);
}
}).then(function(merged){
function putDoc(newDoc, conflicts){
var bulk = conflicts.map(function(revid){
return {
_id: newDoc._id,
_rev: revid,
_deleted: true
};
});
if(!deepEquals(newDoc.data, doc.data)) {
// create new version only if old winning is different
// it should avoid infinite loops between clients
bulk = bulk.concat(newDoc);
}
db.bulkDocs(bulk).then(function(res){
// success
}).catch(function(res){
if(res.status === 409) {
// new conflicts
} else{
// handle error
}
});
}
putDoc(merged, conflicts);
}).catch(function(res){
console.log('change conflict resolution : get error', res);
});
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment