代码之家  ›  专栏  ›  技术社区  ›  user9822291

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

  •  0
  • user9822291  · 技术社区  · 6 年前

    我不知道如何从索引中的Firebase cloud函数向设备发送不同类型的通知。我想发送的js(评论通知)(比如通知)。

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

    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 回复  |  直到 6 年前
        1
  •  0
  •   Cody W.    6 年前

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

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