首页 > 解决方案 > 如何获得不同类型的通知?

问题描述

我不知道如何从我要发送的 index.js 中的 Firebase 云功能向设备发送不同类型的通知(评论通知)(如通知)。

我正在使用此代码向设备发送以下通知,但我不知道如何获得其他通知。

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);   
exports.sendNotification = functions.database.ref('/notification/{user_id}/{notification_id}').onWrite((change, context) => {
const user_id = context.params.user_id;
const notification_id = context.params.notification_id;
console.log('We have a notification to send to  : ', user_id);
const fromUser = admin.database().ref(`/notification/${user_id}/${notification_id}`).once('value');
return fromUser.then(fromUserResult => {
        const from_user_id = fromUserResult.val().from;
        const from_message = fromUserResult.val().message;
        console.log('You have new notification from  : ', from_user_id);
const userQuery = admin.database().ref(`users/${from_user_id}/username`).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 payload1 = {
    notification:{
      title: "some is following you",
      body: `${userName} is following you`,
      icon: "default",
      click_action : "alpha.noname_TARGET_NOTFICATION"
    },
    data:{
       from_user_id:from_user_id
    }
  };
  return admin.messaging().sendToDevice(token_id, payload1).then(result=>{
console.log("notification sent");

});

})
.then(response => {
    console.log('This was the notification Feature');
    return true;
}).catch(error => {
  console.log(error);
  //response.status(500).send(error);
  //any other error treatment
});

  });
});

标签: javascriptandroidnode.jspush-notificationfirebase-cloud-messaging

解决方案


您可以更改发送到 /notification/${user_id}/${notification_id} 节点的内容,以包含可让您在云函数中识别和创建不同通知的字段。

例如,您可以添加一个类型字段,然后:

return fromUser.then(fromUserResult => {
    const from_user_id = fromUserResult.val().from;
    const from_message = fromUserResult.val().message;
    const from_type = fromUserResult.val().type;

然后您可以根据类型构建通知:

if(from_type === NOTIFICATION_FOLLOW){
   payload1 = {
    notification:{
      title: "some is following you",
      body: `${userName} is following you`,
      icon: "default",
      click_action : "alpha.noname_TARGET_NOTFICATION"
    },
    data:{
       from_user_id:from_user_id
    }
  };
}else{
  //set payload1 for a different notification
}

添加有效负载所需的任何字段并根据需要扩展控制结构。


推荐阅读