-
-
Save raytrask/5b087854d68fb2e6857d1667e051e3ae to your computer and use it in GitHub Desktop.
Upsert Parse Cloud
This file contains hidden or 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
// Takes 3 parameters: | |
// class: the object type to update; a single String. | |
// restrictions: the set of column restrictions; a Dictionary. | |
// updates: the set of column updates; a Dictionary. | |
Parse.Cloud.define("upsert", function(request, response) { | |
var query = new Parse.Query(request.params.class); | |
var restrictions = JSON.parse(request.params.restrictions); | |
for (var key in restrictions) { | |
query.equalTo(key, restrictions[key]); | |
} | |
query.find().then(function(results) { | |
var updates = JSON.parse(request.params.updates); | |
if (results.length > 0) { | |
for (var i = 0; i < results.length; i++) { | |
for (var key in updates) { | |
results[i].set(key, updates[key]); | |
} | |
} | |
Parse.Object.saveAll(results).then(function(results){ | |
response.success(results.length + " object(s) were updated!"); | |
},function(error){ | |
response.error(error); | |
}); | |
} else { | |
var objectClass = Parse.Object.extend(request.params.class); | |
var object = new objectClass(); | |
for (var key in updates) { | |
object.set(key, updates[key]); | |
} | |
object.save(null, { | |
success: function(obj) { | |
response.success("1 new object was inserted!"); | |
}, | |
error: function(error) { | |
response.error(error); | |
} | |
}); | |
} | |
}, function(error) { | |
response.error(error); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment