如何获得不同类型的通知?

时间:2018-05-21 12:36:03

标签: javascript android node.js push-notification firebase-cloud-messaging

我不知道如何从我想发送的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
});

  });
});

1 个答案:

答案 0 :(得分:0)

您可以更改发送到/ 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
}

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