Как я могу получить различные типы уведомлений? - PullRequest
0 голосов
/ 21 мая 2018

Я не знаю, как отправлять различные типы уведомлений на устройство из облачной функции Firebase в index.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 Ответ

0 голосов
/ 21 мая 2018

Вы можете изменить то, что вы отправляете на узел / messages / $ {user_id} / $ {messages_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
}

Добавить все поля, необходимые для вашей полезной нагрузки и расширить контрольструктура по мере необходимости.

...