我有一个 firebase 云功能,当新的“紧急情况”添加到数据库时,它应该向最近的 5 部手机发送通知。我编写的代码确实会向最近的 5 部手机发送通知,但它会一遍又一遍地发送相同的通知。当我的用户登录或注销时,情况会变得更糟,因为它会发送更多信息。我很困惑为什么我的云函数不只运行一次然后终止。
这是我的云函数的代码:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.sendPushNotificationAdded = functions.database.ref('/emergencies/{id}').onCreate(event => {
return admin.database().ref('/tokens').on('value', function(snapshot) {
var efarArray = snapshotToArray(snapshot, event.data.child('latitude').val(), event.data.child('longitude').val());
efarArray.sort(function(a, b) {
return a.distance - b.distance;
});
var payload = {
notification: {
title: "NEW EMERGANCY!",
body: "Message from Patient: " + event.data.child('other_info').val(),
//badge: '1',
sound: 'default',
}
};
var options = {
priority: "high",
timeToLive: 0
};
tokens_to_send_to = [];
if(efarArray.length >= 5){
//only send to the 5 closest efars
for (var i = 4; i >= 0; i--) {
tokens_to_send_to.push(efarArray[i].token);
}
}else{
for (var i = efarArray.length - 1; i >= 0; i--) {
tokens_to_send_to.push(efarArray[i].token);
}
}
//TODO: send a messaged back to patient if no efars respond or are found?
return admin.messaging().sendToDevice(tokens_to_send_to, payload, options).then(response => {
});
});
});
//code for function below from https://ilikekillnerds.com/2017/05/convert-firebase-database-snapshotcollection-array-javascript/
function snapshotToArray(snapshot, incoming_latitude, incoming_longitude) {
var returnArr = [];
snapshot.forEach(function(childSnapshot) {
var distance_to_efar = distance(childSnapshot.child('latitude').val(), childSnapshot.child('longitude').val(), incoming_latitude, incoming_longitude);
var item = {
latitude: childSnapshot.child('latitude').val(),
longitude: childSnapshot.child('longitude').val(),
token: childSnapshot.key,
distance: distance_to_efar
};
returnArr.push(item);
});
return returnArr;
};
如果需要更多说明或代码,请告诉我。我一直坚持这个...
最佳答案
不要使用 on()与云功能。这几乎从来都不是正确的使用方法,因为它添加了一个监听器,可以在数据库更改时调用任意次数。使用 once()获取单个快照并据此采取行动。
此外,当该函数中的所有异步工作完成时,您必须从解析的函数返回一个 promise 。 on() 不返回 promise ,因此您的函数也没有这样做。
您可能想研究一些 official sample code并遵循那里建立的模式。
关于android - Firebase Cloud Function 向相同的设备发送多个相同的通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49352440/