首页 > 解决方案 > 用于向令牌集合发送 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);
          });
  
  });

我无法从数据库中获取令牌。它为空或未定义。任何人都可以帮助我完成该功能的第二部分吗?提前非常感谢!

标签: google-cloud-functionsgoogle-cloud-messaging

解决方案


感谢弗兰克的提示!我设法用这段代码解决了这个问题,以防有人需要它:

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;
}

推荐阅读