google-cloud-functions - 用于向令牌集合发送 fcm 通知的云功能
问题描述
每当我的数据库发生新的更新时,我都会尝试发送通知。我有 onUpdate 方面的工作,但我是 FCM 的新手,我被困在发送通知中。设备集合的结构是:
+devices/
+tokenId/
-tokenId:njurhvnlkdnvlksnvlñaksnvlkak
-userId:nkjnjfnwjfnwlknlkdwqkwdkqwdd
我现在拥有的被空值 token 卡住的函数是:
const functions = require('firebase-functions');
const admin = require("firebase-admin");
admin.initializeApp();
const db = admin.firestore();
const settings = { timestampsInSnapshots: true };
db.settings(settings);
.....
exports.fcmSend = functions.firestore
.document(`chats/{chatId}`).onUpdate((change, context) => {
const messageArray = change.after.data().messages;
const message = messageArray[(messageArray.length-1)].content
if (!change.after.data()) {
return console.log('nothing new');
}
const payload = {
notification: {
title: "nuevo co-lab",
body: message,
}
};
return admin.database().ref(`/devices`)
.once('value')
.then(token => token.val())
.then(userFcmToken => {
console.log("Sending...", userFcmToken);
return admin.messaging().sendToDevice(userFcmToken, payload)
})
.then(res => {
console.log("Sent Successfully", res);
})
.catch(err => {
console.log("Error: ", err);
});
});
我无法从数据库中获取令牌。它为空或未定义。任何人都可以帮助我完成该功能的第二部分吗?提前非常感谢!
解决方案
感谢弗兰克的提示!我设法用这段代码解决了这个问题,以防有人需要它:
const payload = {
notification: {
title: "nuevo mensaje de co-lab",
body: message,
}
};
// Get the list of device tokens.
const allTokens = await admin.firestore().collection('devices').get();
const tokens = [];
allTokens.forEach((tokenDoc) => {
tokens.push(tokenDoc.id);
});
if (tokens.length > 0) {
// Send notifications to all tokens.
return await admin.messaging().sendToDevice(tokens, payload);
}else {
return null;
}
推荐阅读
- css - 缩小时的Gridview空白
- java - 当jsp调用servlet并重定向回同一个jsp时如何保留jsp页面上的字段值
- python - 来自 pixle 的 pong 与 CNN 和策略梯度
- reactjs - 在 Redux 中测试动作创建者时如何模拟 Firebase SDK?
- android - 尝试使用 HeapAnalytics 时出现 HeapGradleException
- coronasdk - 电晕几个transition.to失相
- scala - 收集 Akka Actor 系统指标
- google-api - Google Drive API 文件权限不足错误
- javascript - 将 chart.js 用于 Polar 图表,如何为自定义宽度创建每个可见值
- firebase - dynamic_link_first_open 事件是否也会触发 first_open?