Last active
August 29, 2015 14:02
-
-
Save jeffmarshall/0261dfa3808e11752f22 to your computer and use it in GitHub Desktop.
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
// a function to make sure you're always updating | |
// the newest version of a document. | |
// | |
// It will fight to apply your `operation`. | |
function updateDocument( | |
id, // id of the document to update | |
operation, // function that will alter the document | |
callback // called when it's done | |
){ | |
var that_function = this; | |
var those_arguments = arguments; | |
db.get(id, function(error_getting_doc, doc){ | |
if(error_getting_doc){ | |
return callback(error_getting_doc, null) | |
} | |
// enclose this in a `try` statement so that you can | |
// throw an error inside your operation if you need to | |
try{ | |
var updated_doc = operation(doc); | |
} catch(update_error){ | |
return callback(error, null) | |
} | |
// your update operation needs to return the document | |
// you want to insert | |
if (updated_doc == undefined) return callback({ | |
error: "operation_error", | |
message: "operation returned undefined" | |
}) | |
// here we try to insert the updated document | |
db.insert(updated_doc, function(error, result){ | |
if(error){ | |
if(error.error == 'conflict'){ | |
// if there is a conflict error, call the | |
// uppermost function again with the same | |
// arguments | |
return that_function.apply(those_arguments) | |
} | |
// if the error wasn't caused by a conflict, | |
// return it in the callback | |
return callback(error, null) | |
} | |
// if there was no error, your document has | |
// been successfully updated | |
return callback(null, result) | |
}) | |
}) | |
} | |
// Example | |
updateDocument( | |
'97969a83-5168-df82-a9bc-eb9f2c043dff', | |
function(doc){ | |
doc.updated = (new Date()).getTime(); | |
return doc | |
}, | |
function(error, callback){ | |
if(error){ | |
return console.log('there was a real error') | |
} | |
return console.log('document updated') | |
} | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment