删除请求后,Firebase数据库onWrite的云功能触发两次

时间:2017-11-18 20:43:53

标签: node.js function firebase-realtime-database firebase-cloud-messaging

我有一个朋友请求函数,在发送请求时会触发该函数,但如果用户拒绝该请求,则会再次触发onWrite。     如果删除了firebase db中的请求节点,我该如何返回promise。

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);
            });
    });
});

1 个答案:

答案 0 :(得分:0)

听起来您只希望在创建请求时触发云功能。您可以通过注册onCreate

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

有关详细信息,请参阅documentation on setting event handlers