Skip to content

Instantly share code, notes, and snippets.

@cameronmoreau
Created June 6, 2015 19:06
Show Gist options
  • Save cameronmoreau/72d596d96ebc2ec674e4 to your computer and use it in GitHub Desktop.
Save cameronmoreau/72d596d96ebc2ec674e4 to your computer and use it in GitHub Desktop.
Upload hundreds of Prase objects at once
/**
* To use this in your Prase project:
* Upload this gist as main.js in Cloud Code for Parse
*
* Create a PFObject from "fileTestSave"
* Store all data into a JSON Array, and attach as a PFFile
*
* Then run the "RemoveFiles" background job daily to get rid of
* the stored files
*
* http://cameronmoreau.org
*/
//Upload JSON file
Parse.Cloud.afterSave('fileTestSave', function(request, response) {
var file = request.object.get('testFile');
var fileUrl = file['url']();
Parse.Cloud.httpRequest({
method: 'GET',
url: fileUrl,
success: function(httpResponse) {
var saveData = [];
var json = JSON.parse(httpResponse.text);
//Iterate though JSON
for(var i = 0; i < json.length; i++) {
var jsonObject = json[i];
//Extend Parse Object and store values from JSON file
var User = Parse.Object.extend('user');
var userObject = new User();
userObject.set('name', jsonObject['name']);
userObject.set('email', jsonObject['email']);
userObject.set('phone', jsonObject['phone']);
saveData.push(userObject);
}
Parse.Object.saveAll(saveData, {
error: function(error) {
response.error('An error occured while saving JSON object: ' + error);
}
});
},
error: function(httpResponse) {
response.error('httpResponse error');
}
});
});
//Remove stored JSON files
Parse.Cloud.job('RemoveFiles', function(request, response) {
Parse.Cloud.useMasterKey();
var FileTestSave = Parse.Object.extend("fileTestSave");
var query = new Parse.Query(FileTestSave);
query.each(function(file) {
file.destroy();
}).then(function() {
response.success('All JSON files cleared');
}, function(error) {
response.error('JSON files could not be deleted: ' + error);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment