Node.js 无法使用云函数发送FCM消息
我们正在开发一个聊天应用程序,并使用云功能向使用FCM注册令牌的设备发送数据通知。代码如下:Node.js 无法使用云函数发送FCM消息,node.js,firebase,google-cloud-messaging,google-cloud-functions,google-cloud-firestore,Node.js,Firebase,Google Cloud Messaging,Google Cloud Functions,Google Cloud Firestore,我们正在开发一个聊天应用程序,并使用云功能向使用FCM注册令牌的设备发送数据通知。代码如下: const functions = require('firebase-functions'); const admin = require('firebase-admin'); admin.initializeApp(functions.config().firebase); exports.createMessage = functions.firestore .document('me
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.createMessage = functions.firestore
.document('messages/{messageId}')
.onCreate(event => {
const db = admin.firestore();
var newValue = event.data.data();
var recipient = newValue.recipient_id;
var msg = newValue.message;
var sender = newValue.sender_id;
var senderRef = db.collection('users').doc(sender);
var recipientRef = db.collection('users').doc(recipient);
const senderObj = new Promise(
function(resolve, reject) {
senderRef.get()
.then(doc => {
if (!doc.exists) {
console.log('No such User document!');
reject(new Error('No such document!'));
} else {
console.log('Document data:', doc.data());
resolve(doc.data());
}
})
.catch(err => {
console.log('Error getting document', err);
reject(err);
});
});
const recipientObj = new Promise(
function(resolve, reject) {
recipientRef.get()
.then(doc => {
if (!doc.exists) {
console.log('No such User document!');
reject(new Error('No such document!'));
} else {
console.log('Document data:', doc.data());
resolve(doc.data());
}
})
.catch(err => {
console.log('Error getting document', err);
reject(err);
});
});
return Promise.all([senderObj, recipientObj]).then(results => {
var senderDetails = results[0];
var recipientDetails = results[1];
var payload = {
"data": {
"title": String(senderDetails.first_name),
"body": String(msg),
"recipientId": String(recipient),
"senderId": String(sender),
"senderImage": String(senderDetails.avatar),
"createdTime": String(newValue.created_time),
"chatType": "one",
"messageId": String(event.params.messageId)
}
};
var options = {
priority: "high"
};
/*
if (recipientDetails.device_type != "android"){
payload["content_available"] = true;
payload["priority"] = "high";
}
*/
admin.messaging().sendToDevice(recipientDetails.device_token, payload, options)
.then(function(response) {
console.log("Message sent: ", response);
})
.catch(function(error) {
console.log("Error sending message: ", error, payload);
});
});
});
这项技术正在开发中,直到上周才能够正常向设备发送通知。它首先开始将消息延迟5-10分钟,现在我们根本没有收到任何通知。clould函数上的日志显示消息已成功传递:(
Firestore/Cloud函数最近有什么变化吗?或者代码有什么问题吗?任何指针都将受到高度赞赏。您需要从
sendToDevice()返回Promise
:
谢谢鲍勃,这是工作与回报,但我相信这是工作没有承诺回报以及直到上周!无论如何谢谢你的回答。
return admin.messaging().sendToDevice(...) // ADDED return