当用户收到带有以下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。
我现在的问题是,我如何才能检索发送方用户名并仅在接收方设备上显示通知?
答案 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,因此之后的代码将无法工作,并且与问题无关。通过这种方式缩小问题的范围,可以增加找到原因的机会。或者更糟的是,它减少了我们需要查看的代码,从而增加了有人发现问题并回答的机会。