我正在尝试基于用户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);
});
});
});
它不显示任何日志消息或任何通知。
答案 0 :(得分:0)
您使用了不正确的承诺。触发函数完成后,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);
});
});