I have created a Background Job in Parse Cloud Code that sends out email notifications based on a date in one of my Parse classes.
Here is the idea: Query the class that contains the date. Iterate over each object returned and check the date field. If the date is equal to today, send out an email notification, change the date to null and save it back to Parse.
However, it seems that not all the objects are saved back to Parse. I suspect this an issue with my promise chains, but I am having a hard time diagnosing the exact issue or how to fix it. Below is relevant code
Parse.Cloud.job("dailySendNotificationsJob", function(request, status) {
var Mailgun = require('mailgun');
Mailgun.initialize(...);
// Set up to modify user data
Parse.Cloud.useMasterKey();
// Query for all users
var query = new Parse.Query("Subscription");
query.equalTo("onHiatus", true);
query.include("fromUser");
query.include("toBusiness");
query.each(function(subscription) {
var user = subscription.get("fromUser");
var vendor = subscription.get("toBusiness");
var email = user.get("email");
var today = new Date();
var todayDd = today.getDate();
var todayMm = today.getMonth()+1; //January is 0!
var todayYyyy = today.getFullYear();
var onHiatusUntil = subscription.get("onHiatusUntil");
ddHiatus = onHiatusUntil.getDate();
mmHiatus = onHiatusUntil.getMonth()+1;
yyyyHiatus = onHiatusUntil.getFullYear();
// Check that date is equal to today
if ( onHiatusUntil && todayDd==ddHiatus && todayMm == mmHiatus && todayYyyy == yyyyHiatus) {
subscription.set("onHiatus", false);
subscription.set("onHiatusUntil", null);
subscription.save(null, {
success:function(subscription){
// This never executes!
},
error: function(error){
}
}).then(function(){
// This never executes
console.log("Save subscriptions successful");
},
function(error){
status.error("Uh oh, something went wrong saving subscription object");
});
// Set hiatus end successful
Mailgun.sendEmail({
to: "xxxxx@fake.com",
from: "Mailgun@CloudCode.com",
subject: "Notification",
text: "EMAIL TEXT"
}, {
success: function(httpResponse) {
console.log(httpResponse);
response.success("Email sent!");
},
error: function(httpResponse) {
console.error(httpResponse);
response.error("Uh oh, something went wrong");
}
});
}
}).then(function() {
// Set the job's success status
status.success("Subscriptions successfully fetched");
}, function(error) {
// Set the job's error status
status.error("Uh oh, something went wrong fetching subscriptions.");
});
});
This line console.log("Save subscriptions successful");
in the subscriptions.save() promise chain does not ever get executed - even when the subscription object is successfully saved to Parse.
Additionally, if there are more than 5 subscription objects returned by the query, only the first 5 are successfully saved back to Parse. Any additional saves are not executed and email notifications are not sent.
Aucun commentaire:
Enregistrer un commentaire