首页 > 解决方案 > 节点 JS FCM 令牌未向用户发送通知

问题描述

我正在尝试根据用户 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);
            });
    });
});

它不显示任何日志消息或任何通知。

标签: androidnode.jsfirebasefirebase-cloud-messaginggoogle-cloud-functions

解决方案


您正在使用不正确的承诺。当触发函数完成时,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);
    });                
});

推荐阅读