Reputation: 444
I was hoping to add an after save trigger to Parse.com that notified me when a certain type of user's account was updated. In this case, if column "user_ispro" is true in Parse.User I want to be emailed after the save (this column is either null to true). I added the code below but I am getting emailed on every update instead of just my query. Thoughts?
Parse.Cloud.afterSave(Parse.User, function(request) {
var Mandrill = require('mandrill');
query = new Parse.Query(Parse.User);
query.equalTo("user_ispro", true);
query.find({
success: function(results) {
Mandrill.initialize('xxxx');
Mandrill.sendEmail({
message: {
text: "Email Text",
subject: "Subject",
from_email: "[email protected]",
from_name: "Test",
to: [{
email: "[email protected]",
name: "Test"
}]
},
async: true
}, {
success: function(httpResponse) {
console.log(httpResponse);
response.success("Email sent!");
},
error: function(httpResponse) {
console.error(httpResponse);
response.error("Uh oh, something went wrong");
}
});
},
error: function() {
response.error("User is not Pro");
}
});
});
Upvotes: 0
Views: 2163
Reputation: 444
Thanks Bjorn, I ended up using a count query instead of a find. If the number of results is greater than 0 then send the email. Also realized that I was not querying for the specific objectId so this was my final code:
Parse.Cloud.afterSave(Parse.User, function(request) {
var Mandrill = require('mandrill');
query = new Parse.Query(Parse.User);
query.equalto("objectId",request.object.id);
query.equalTo("user_ispro", true);
query.count({
success: function(count) {
if (count > 0) {
Mandrill.initialize('xxxx');
Mandrill.sendEmail({
message: {
text: "Email Text",
subject: "Subject",
from_email: "[email protected]",
from_name: "Test",
to: [{
email: "[email protected]",
name: "Test"
}]
},
async: true
}, {
success: function(httpResponse) {
console.log(httpResponse);
response.success("Email sent!");
},
error: function(httpResponse) {
console.error(httpResponse);
response.error("Uh oh, something went wrong");
}
});
},
else {
console.log("User is not Pro");
}
});
});
Upvotes: 0
Reputation: 9912
The success callback of a query is always executed (read: when the query succeeds), which is true in almost every case. You are expecting the query to fail when there are no results, which is a wrong assumption.
You should add a check if the result is empty and only trigger the email sending when there are actual results. The error callback only gets fired if there was an error, an empty result is not an error (obviously).
Upvotes: 1