NodeJS Firebase云函数触发Firebase消息传递不发送通知

xqkwcwgp  于 2023-06-22  发布在  Node.js
关注(0)|答案(1)|浏览(106)

bounty将在6天内到期。回答此问题可获得+100声望奖励。Chris希望引起更多关注这个问题。

我想在一个叫notifications的用户的集合中添加文档时,通过云消息发送一个PushNotification。我按照文档中的建议将token保存在名为messagingTokens的字段中的arrayUnion中。
此外,只有当名为isPushEnabled的字段为true时,才应发送通知。根据这些信息,我构建了这个cloud function并成功部署了它:

const notificationPath = "users/{userId}/notifications/{notificationId}";
exports.sendNotification = onDocumentCreated(notificationPath, async (event) => {
    const data = event.data.after.data();
    const senderUid = data["senderUid"];
    const recieverUid = data["recieverUid"];
    const notificationOption = data["notificationOption"];

    if (notificationOption == "recievedFriendRequest") {
        await onSentFriendRequest(senderUid, recieverUid);
    }
});

async function onSentFriendRequest(ownerId, userId) {
    // Get the owners details
    const owner = await admin.firestore().collection("allUsers").doc(ownerId).get();

    // Get the users details
    const user = await admin.firestore().collection("allUsers").doc(userId).get();

    const userHasNotificationsEnabled = user.data().isPushEnabled;

    if (userHasNotificationsEnabled) {
        await admin.messaging().send(
            user.messagingTokens,
            {
                notification: {
                    title: "Neue Freundschaftsanfrage",
                    body: owner.userName + " möchte mit dir befreundet sein.",
                },
                data: {
                    ownerId: ownerId,
                    userId: userId,
                    notificationOption: "recievedFriendRequest",
                },
            },
            {
                // Required for background/quit data-only messages on iOS
                contentAvailable: true,
                // Required for background/quit data-only messages on Android
                priority: "high",
            },
        );
    }
}

就像我说的,部署很成功。但是当一个文档被添加到notifications-collection时什么也没有发生。
Firebase-Console中,我看到该函数被触发,但没有看到其他任何内容。我试着在日志中心找,但我找不到任何东西。
我做错了什么?或者在哪里可以看到功能是否失败?如果你需要更多的信息,请告诉我。

编辑

我有一个关于maxScale的错误,我可以通过在我的index.js文件中添加这一行来修复:

setGlobalOptions({maxInstances: 10})

下面是我的firebase.json

"frameworksBackend": {
    "region": "us-central1",
    "maxInstances": 10
  }

现在我在日志中看不到任何错误。但还是不行。我试着做了一些logs的调用:

functions.logger.log("User has push enabled");

但我也没在任何地方看到。

tvmytwxo

tvmytwxo1#

const admin = require('firebase-admin');

admin.initializeApp();

使用Firebase Functions时,应始终使用onCreate触发器而不是onDocumentCreated函数来侦听文档创建,因为Firebase Functions SDK中不存在该函数。随着复杂性和变化程度的增加,写作可以产生更有趣和更吸引人的内容,让读者更好地理解和欣赏他们正在消费的单词。

exports.sendNotification = functions.firestore
    .document(notificationPath)
    .onCreate(async (snapshot, context) => {
        // Retrieve the document data
        const data = snapshot.data();
        const senderUid = data.senderUid;
        const receiverUid = data.receiverUid;
        const notificationOption = data.notificationOption;

        if (notificationOption === "receivedFriendRequest") {
            await onSentFriendRequest(senderUid, receiverUid);
        }
    });

更新代码中的用户令牌是必不可少的。要检索用户的messagingTokens,代码需要获取Firestore文档快照并说明messagingTokens字段。为此,user.data必须使用www.example.com().messagingTokens。因此,代码应更改如下:user.data().messagingTokens而不是user. messagingTokens。

const userHasNotificationsEnabled = user.data().isPushEnabled;

if (userHasNotificationsEnabled) {
    const tokens = user.data().messagingTokens;

    await admin.messaging().sendMulticast({
        tokens: tokens,
        notification: {
            title: "Neue Freundschaftsanfrage",
            body: `${owner.data().userName} möchte mit dir befreundet sein.`,
        },
        data: {
            ownerId: ownerId,
            userId: userId,
            notificationOption: "receivedFriendRequest",
        },
    });
}

你可以在相关点添加console.log语句。

console.log("User has push enabled");

希望这有帮助!

相关问题