使用Firebase发送通知时用户名为空

时间:2019-02-13 14:45:31

标签: javascript firebase firebase-cloud-messaging firebase-admin

当用户收到带有以下JavaScript代码的新消息时,我想向他们发送通知

const functions = require('firebase-functions');

const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);



exports.pushNotification = functions.database.ref('/messages/{user_id}/{message_id}').onWrite( (change, context) => {

const user_id = context.params.user_id;
const message_id = context.params.message_id;

console.log('We Have A Notification for :', user_id);

if (!change.after.val()){
    return console.log("A Notification Has Been Deleted From The Database: ", message_id)
}

const fromUser = admin.database().ref(`/messages/${user_id}/${message_id}`).once('value');

return fromUser.then(fromUserResult => {

    const from_user_id = fromUserResult.val().from;
    console.log("You have new notification from : ", from_user_id)

    const userQuery = admin.database().ref(`/Users/${from_user_id}/name`).once('value');
    const deviceToken = admin.database().ref(`/Users/${user_id}/device_token`).once('value');

    return Promise.all([userQuery, deviceToken]).then(result => {

        const userName = result[0].val();
        const token_id = result[1].val();

        const payload = {
            notification: {
                title: "Chat+",
                body: `You have a new notification from ${userName}`,
                icon: "default",
                click_action: "com.mani.eric.quickch_TARGET_NOTIFICATION"
            },

        };

        return admin.messaging().sendToDevice(token_id, payload ).then(Response =>{ 
            console.log('this is the notification')
        });


    });

});

}); 

该通知实际上已传递,但在两个设备(发送者和接收者都收到相同的通知)上,发送者的用户名为null。

我现在的问题是,我如何才能检索发送方用户名并仅在接收方设备上显示通知?

1 个答案:

答案 0 :(得分:0)

您在触发该函数的路径上有一个类型:

functions.database.ref('/messages/{user_id/{message_id}')

应该是:

functions.database.ref('/messages/{user_id}/{message_id}')

user_id之后加上右括​​号。

请阅读how to create a minimal, complete, verifiable example,因为您共享的代码比重现该问题所需的代码要复杂得多。例如,您的console.log('We Have A Notification for :', user_id);应该已经显示user_id为null,因此之后的代码将无法工作,并且与问题无关。通过这种方式缩小问题的范围,可以增加找到原因的机会。或者更糟的是,它减少了我们需要查看的代码,从而增加了有人发现问题并回答的机会。