Node JS FCM токен не отправляет уведомление пользователю - PullRequest
1 голос
/ 12 июня 2019

Я пытаюсь отправить уведомление на основе токена пользователя FCM, я использовал функцию firebase для успешной отправки уведомления, если есть какие-либо изменения в базе данных firebase для этого конкретного пользователя.Но в настоящее время функция node.JS не предоставляет журналов сообщений / уведомлений, отправляемых пользователю.Помогите мне решить эти проблемы.

//import firebase functions modules
const functions = require('firebase-functions');
//import admin module
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);


// Listens for new messages added to messages/:pushId
exports.pushNotification = functions.database.ref('/Notification/{receiver_id}/push_id/{job_id}').onWrite((data, context) => {

  const receiver_id = context.params.receiver_id;
  const job_id = context.params.job_id;
  console.log('Start');
  console.log('receiverID : ' + receiver_id);
  console.log('jobID : ' + job_id);

  const DeviceToken = admin.database().ref(`/User/${receiver_id}/fcmtoken`).once('value');

    return DeviceToken.then(result => 
    {
        const token_id = result.val();
        console.log(token_id);
        const payload = 
        {
            notification:
            {
                title: "New Job Request",
                body: `JobID ` + job_id,
                tag: collapseKey,
                icon: "default",
                color: '#18d821',
                sound: 'default',
            }
        };

        return admin.messaging().sendToDevice(token_id, payload)
        .then(response => 
            {
                console.log('This was a notification feature.');
                return null;

            })
            .catch(function(error) {
                console.log('Error sending message:', error);
            });
    });
});

В нем не отображаются сообщения журнала или уведомления.

1 Ответ

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

Вы используете неверное обещание. SendToDevice может быть прерван, когда функция триггера завершит работу, потому что он не ожидает этого обещания.

exports.pushNotification = functions.database.ref('/Notification/{receiver_id}/push_id/{job_id}').onWrite((data, context) => {

  const receiver_id = context.params.receiver_id;
  const job_id = context.params.job_id;
  console.log('Start');
  console.log('receiverID : ' + receiver_id);
  console.log('jobID : ' + job_id);

  const DeviceToken = admin.database().ref(`/User/${receiver_id}/fcmtoken`).once('value');

  return DeviceToken.then(result => 
    {
        const token_id = result.val();
        console.log(token_id);
        const payload = 
        {
            notification:
            {
                title: "New Job Request",
                body: `JobID ` + job_id,
                tag: collapseKey,
                icon: "default",
                color: '#18d821',
                sound: 'default',
            }
        }; 
        return admin.messaging().sendToDevice(token_id, payload) 
    })
    .then(response => {
        console.log('This was a notification feature.');
        return null; 
    })
    .catch(function(error) {
        console.log('Error sending message:', error);
    });                
});
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...