I have a cloud function that takes in a request and creates objects as well as associates them in a chain of promises. Without a beforeSave this function works fine but the beforeSave exists to prevent duplicate entries of email addresses in the Email Class.
REQUEST
{
"projectDescription": "Testing saveProject",
"projectTitle": "This is only a test, in the event of a real post this will have an actual description",
"isEmailEnabled": true,
"shareEmails": [
"test1@gmail.com",
"test2@gmail.com",
"test3@gmail.com"
],
"userId": "1234"
}
FUNCTION
Parse.Cloud.define("saveProject", function(request, response) {
var emails = request.params.shareEmails;
var user = request.params.userId;
var projectDescription = request.params.projectDescription;
var projectTitle = request.params.projectTitle;
var emailStatus = request.params.isEmailEnabled;
var ProjectClass = Parse.Object.extend("Project");
var EmailsClass = Parse.Object.extend("Email");
var EmailsClassAssignment = Parse.Object.extend("EmailAssignment");
var project = new ProjectClass();
var projectO;
var emailQueryArray;
project.set("title", projectTitle);
project.set("createdBy", {
"__type": "Pointer",
"className": "_User",
"objectId": user
});
project.set("description", projectDescription);
project.set("status", true);
project.set("emailShareEnabled", emailStatus);
project.save().then(function(projectObject) {
projectO = projectObject;
}).then(function() {
emails.forEach(function(emailAddress) {
var email = new EmailsClass();
email.set("address", emailAddress);
email.save();
});
}).then(function() {
emails.forEach(function(emailQuery) {
var queryEmail = new Parse.Query("Email");
queryEmail.equalTo("address", emailQuery);
queryEmail.find().then(function(results) {
emailObject = results;
console.log(emailObject);
});
});
});
});
beforeSave Code
Parse.Cloud.beforeSave("Email", function(request, response) {
var query = new Parse.Query("Email");
// Gets the email key value (string) before object is saved
query.equalTo("address", request.object.get("address"));
// Checks to see if an object for that email already exists
query.first({
success: function(object) {
if (object) {
response.error("This email already exisits");
} else {
response.success();
}
},
error: function(error) {
response.error("Could not determine if this email exists");
}
});
});
Is there a way to account for the beforeSave in the callback from saving the email object so that I ensure the object is there to query against?
I need the objects to be there so that I can get the Id for each and create a pointer in the Email assignments Class.
Would be happy to further explain any part of the code or function as a whole.