[英]User name empty when sending notification with firebase
当用户收到带有以下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。
我现在的问题是,我如何检索发送者用户名并仅在接收者设备上显示通知?
您在触发函数的路径上有一个类型:
functions.database.ref('/messages/{user_id/{message_id}')
应该:
functions.database.ref('/messages/{user_id}/{message_id}')
因此,在user_id
之后加上user_id
括号。
请阅读如何创建一个最小,完整,可验证的示例 ,因为共享的代码比重现该问题所需的代码要复杂得多。 例如,您的console.log('We Have A Notification for :', user_id);
已经应该显示user_id
为null,因此之后的代码将无法工作,并且与问题无关。 通过这种方式缩小问题的范围,可以增加找到原因的机会。 或在最坏的情况下,它减少了我们需要查看的代码,从而增加了有人发现并回答问题的机会。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.