Skip to content

Instantly share code, notes, and snippets.

@emertechie
Created March 4, 2014 13:18
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 emertechie/9346377 to your computer and use it in GitHub Desktop.
Save emertechie/9346377 to your computer and use it in GitHub Desktop.
Parse.Cloud.beforeSave("TestObject", function(request, response) {
ensureNotStale(request.object, response.error, function() {
// Update is not stale. Add any other code here
console.log('doing some work here with the fresh object');
response.success();
});
});
function ensureNotStale(incommingObj, reject, resolve) {
var versionAttrName = "version";
var className = incommingObj.className;
var id = incommingObj.id;
if (incommingObj.isNew()) {
console.log(className + ' "' + id + '" is new so setting ' + versionAttrName + ' to 1');
incommingObj.set(versionAttrName, 1);
resolve();
return;
}
var incommingVersion = incommingObj.get(versionAttrName);
incommingObj.increment(versionAttrName);
var query = new Parse.Query(className);
query.get(id, {
success: function(latest) {
var latestVersion = latest.get(versionAttrName);
var upToDate = incommingVersion === latestVersion;
if (!upToDate) {
var msg = 'StaleUpdate: Could not update stale ' + className + ' "' + id + '". ' +
'Incomming version was ' + incommingVersion + ', latest is ' + latestVersion;
console.log(msg);
reject(msg);
} else {
// console.log(className + ' "' + id + '" is up to date at version ' + latestVersion + '. Letting op proceed');
resolve();
}
},
error: function(object, error) {
if (error.code === Parse.Error.OBJECT_NOT_FOUND) {
// hmm, doesn't exist. Oh well, carry on
console.warn('Could not find previous ' + className + ' with ID "' + id + '"');
resolve();
} else {
console.error('Could not load previous ' + className + ' with ID "' + id + '". Error was: ' + error);
reject('Error checking for previous version of ' + className);
}
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment