Как отправить уведомление с помощью почтальона на триггере базы данных в реальном времени? - PullRequest
1 голос
/ 23 июня 2019

Я написал облачную функцию в Javascript, которая должна отправлять уведомления, если в базе данных происходят изменения.

Я зарегистрировал значения в коде и даже получаю ответ в admin.messaging (). SendToDevice (token, payload). И все выглядит хорошо из журнала в моей консоли Firebase, но я не получаю никаких уведомлений на моем устройстве. Кроме того, почтальон настроен правильно, потому что я получаю уведомление, когда нажимаю кнопку «Отправить» на почтальоне.

Это мое тело json в Почтальоне

{
  "to" : "dCDqZxTYq3s:APA91bFlbFd3hGUJuvjknPhivRLew69kM4KDrNJAOkIMT5WgsoHr_Uc_41xqeOtQJvMhvXO1S56v4aT_6Zd24rlGoD-AV7pyNFMw8AxdkmwZCS3HYDidO2-xX_Da8IGcuQTN3FrnIYKo",
 "data" : {
    "message" : "This is my data message",
    "title" : "This is my data title",
    "data_type": "direct_message"
  },
  "notification" : {
    "title": "This is a title",
    "text": "this is a notification"
  }
}

Это index.js, где написана моя облачная функция

const functions = require('firebase-functions');

const admin = require('firebase-admin');

admin.initializeApp(functions.config().firebase);

exports.sendNotification = functions.database.ref('/problemDetails/{problemId}').onUpdate((change, context) => {

    const problemId = context.params.problemId;
    console.log("problemId: ", problemId);

    //get the userId of the person receiving the notification because we need to get their token
    const senderId = change.after.child('userId').val();

    //get the status
    const status = change.after.child('status').val();


    // //get the user id of the person who sent the message
    // const senderId = event.data.child('user_id').val();  //THis should be mechID
    // console.log("senderId: ", senderId);



    if(status === 'Price set by mechanic'){
    //get the message
    const message = "The mechanics has set the price for your service. Please check your current order if you have to take any actions.";
    console.log("message: ", message);

    //get the message id. We'll be sending this in the payload
    const messageId = "messageId";
    console.log("messageId: ", messageId);

    //query the users node and get the name of the user who sent the message
    return admin.database().ref("/users/" + senderId).once('value').then(snap => {
        const senderName = snap.child("displayName").val();
        console.log("senderName: ", senderName);

        //get the token of the user receiving the message
        return admin.database().ref("/users/" + senderId).once('value').then(snap => {  //change senderId here to mechId who will be the receiver
            const token = snap.child("messagingToken").val();
            console.log("token: ", token);

            //we have everything we need
            //Build the message payload and send the message
            console.log("Construction the notification message.");
            const payload = {
                data: {
                    data_type: "direct_message",
                    title: "New Message from " + senderName,
                    message: message,
                    message_id: messageId,
                }
            };

            return admin.messaging().sendToDevice(token, payload)
                        .then(function(response) {
                            console.log("Successfully sent message:", response);
                          })
                          .catch(function(error) {
                            console.log("Error sending message:", error);
                          });
        });
    });
}
else{
    return null;
}
});

1 Ответ

0 голосов
/ 23 июня 2019

Я понял это.Это не имеет ничего общего с почтальоном.Я немного запутался.На самом деле, почтальон вообще не нужен.

Проблема в том, что у моей полезной нагрузки нет объекта уведомления, поэтому я не получал никаких уведомлений (хотя сообщение отправлялось и, следовательно, журналы).

Изменение полезной нагрузки на это работает

        const payload = {
                data: {
                    data_type: "direct_message",
                    title: "New Message from " + senderName,
                    message: message,
                    message_id: messageId
                },
                    notification : {
                        title: "This is a title",
                        text: "this is a notification"
                }
            };
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...