适用于 Firebase 数据库的云函数在删除请求后触发两次



我有一个朋友请求函数,它在发送请求时被触发,但如果用户拒绝请求,则会再次触发onWrite。 如果移除了 Firebase 数据库中的请求节点,如何返回承诺。

exports.sendFreindRequestNotification = functions.database.ref('/users/{pushId}')
.onWrite(event => {
    let friendRequest = event.data.current.val();
    let senderUid = friendRequest.requests;
    let receiverUid = friendRequest.uid;
    let promises = [];
    for (key in senderUid) {
        console.log('my Key', key);
    }
    //Some kind of logic to return the the promise if the friend request value is removed from firebase db to avoid firing again.
    if (receiverUid == key) {
        return Promise.all(promises);
    }
    let getInstanceIdPromise =  admin.database().ref(`/users/${receiverUid}/pushToken`).once('value'); 
    let getSenderUidPromise = admin.auth().getUser(key);
    return Promise.all([getInstanceIdPromise, getSenderUidPromise]).then(results => {
        let instanceId = results[0].val();
        let sender = results[1];
        console.log('notifying ' + receiverUid + ' about ' + friendRequest.displayName + ' from ' + key);
        console.log('Sender ', sender);
        let payload = {
            notification: {
                body: 'You have a new friend request from ' + sender.email,
                sound: 'default'
            },
            'data': { 
                'notificationType': "friendRequest" 
          }
        };
        admin.messaging().sendToDevice(instanceId, payload)
            .then(function (response) {
                console.log("Successfully sent message:", response);
            })
            .catch(function (error) {
                console.log("Error sending message:", error);
            });
    });
});

听起来您只希望在创建请求时触发云函数。您可以通过注册onCreate来做到这一点:

exports.sendFreindRequestNotification = functions.database.ref('/users/{pushId}')
.onCreate(event => {

有关详细信息,请参阅有关设置事件处理程序的文档。

相关内容

  • 没有找到相关文章

最新更新