我正在尝试通过Parse Cloud Code在修改某个对象时发送推送通知 - "脏"
我想我差不多了,但收到错误,因为我相信我正在创建一个新用户,而不是查询一个用户。
Parse.Cloud.beforeSave("Fact", function(request, response) {
var dirtyKeys = request.object.dirtyKeys();
for (var i = 0; i < dirtyKeys.length; ++i) {
var dirtyKey = dirtyKeys[i];
if (dirtyKey === "isValid") {
//send push
// Creates a pointer to _User with object id of userId
var targetUser = new Parse.User();
// targetUser.id = userId;
targetUser.id = request.object.userID;
var query = new Parse.Query(Parse.Installation);
query.equalTo('user', targetUser);
Parse.Push.send({
where: query,
data: {
alert: "Your Fact was approved :)"
}
});
return;
}
}
response.success();
});
我发现this post与我的问题有关。我现在的问题是如何在我的beforeSave块中集成用户查询。理想情况下,我会为用户查询创建另一个函数,并将其放在我的beforeSave块中。
** 5/14更新 我接受了@ toddg的建议并修复了之前的保存。以下是我正在尝试做的事情和新错误的更清晰的图片。
答案 0 :(得分:0)
在我进入代码之前,有几点(正如@Subash在评论中指出的那样):
Parse.Push.send
是异步操作,因此您需要确保在推送完成后调用response.success()
。我将使用Promises处理这个问题,因为我认为它们比回调更灵活。如果您不熟悉,请阅读here response.success()
。这是我推荐的做法:
Parse.Cloud.beforeSave("Fact", function(request, response) {
// Keep track of whether we need to send the push notification
var shouldPushBeSent = false;
var dirtyKeys = request.object.dirtyKeys();
for (var i = 0; i < dirtyKeys.length; ++i) {
var dirtyKey = dirtyKeys[i];
if (dirtyKey === "isValid") {
shouldPushBeSent = true;
}
}
if (shouldPushBeSent) {
//send push
// Creates a pointer to _User with object id of userId
var targetUser = new Parse.User();
// targetUser.id = userId;
targetUser.id = request.object.userId;
var query = new Parse.Query(Parse.Installation);
// We want to pass the User object to the query rather than the UserId
query.equalTo('user', targetUser);
Parse.Push.send({
where: query, // Set our Installation query
data: {
alert: "Your fact was approved"
}
}).then(function(){
// Now we know the push notification was successfully sent
response.success();
}, function(error){
// There was an error sending the push notification
response.error("We had an error sending push: " + error);
});
} else {
// We don't need to send the push notification.
response.success();
}
});
顺便说一句,我假设您的Installation类上有一列用于跟踪与每个安装相关联的用户。