我目前正在使用 Parse Cloud 代码后台作业来通知用户在他们指定的半径内发现新的丢失宠物时。
例如,宠物 XYZ 丢失了所有启用推送且在其指定范围内的用户将收到新丢失宠物的推送通知。
我现在的主要问题是,如果丢失的宠物附近有很多用户,推送通知将超过解析的 API 请求限制,因为我目前一次发送一个。
我该如何改进呢?我在想也许使用一个包含所有应该收到通知的 Users_Ids 的数组(每个宠物的文本都是相同的)
到目前为止,这是我的(工作)代码:
检查新宠物的主要工作功能
Parse.Cloud.job("pushRadius", function(request, response) {
Parse.Cloud.useMasterKey();
console.log('pushRadius');
var Pet = Parse.Object.extend("Pet");
var petQuery = new Parse.Query(Pet);
petQuery.equalTo("initialPushSent", false);
petQuery.equalTo("status", "missing");
petQuery.equalTo("deleted", false);
petQuery.find().then(function(pets) {
console.log("found " + pets.length + " pets");
var promises = [];
_.each(pets, function(pet) {
promises.push(checkUsersForPet(pet));
Parse.Cloud.useMasterKey();
pet.set("initialPushSent", true);
pet.save();
});
return Parse.Promise.when(promises);
}).then(function(obj) {
console.log('All Pets checked');
}, function(error) {
console.log('whoops, something went wrong ' + error.message);
});
});
在主函数中为每个找到的宠物获取范围内的用户
function checkUsersForPet(pet){
console.log("check Pet" + pet.id);
var petLocation = pet.get("lastSeenLocation");
var query = new Parse.Query("User");
query.withinKilometers("lastLocation", petLocation, 50);
query.equalTo("pushActivated", true)
query.find().then(function(users) {
console.log("found " + users.length + " users for pet " + pet.id);
var promises = [];
_.each(users, function(user) {
if (petLocation.kilometersTo(user.get("lastLocation")) <= user.get("pushRadius")) {
promises.push(sendUsersPush(user, pet));
}
});
return Parse.Promise.when(promises);
}).then(function(obj) {
console.log('All Users checked');
}, function(error) {
console.log('whoops, something went wrong ' + error.message);
});
}
发送用户通知并为丢失的宠物添加一个新的通知对象推送发送应使用一组用户通道完成,仅计为 1 个 API 请求
function sendUsersPush(user, pet){
console.log("send user "+ user.id +" push for pet" + pet.id)
Parse.Push.send({
channels: ["user_" + user.id],
data: {
badge: "Increment",
alert: "Neues vermisstes Tier " + pet.get("title") + " im Umkreis"
}
}, {
success: function() {
console.log("Push sent to user" + user.id + "for pet " + pet.id);
},
error: function(error) {
console.error("Got an error " + error.code + " : " + error.message);
}
});
var Notification = Parse.Object.extend("Notification");
var notification = new Notification();
notification.set("read", false);
notification.set("user", user);
notification.set("pet", pet);
notification.set("type", "new");
notification.set("petName", pet.get("title"));
notification.save(null, {
success: function(notification) {
},
error: function(notification, error) {
}
});
}