gpt4 book ai didi

node.js - 获取用户 ID 后,Firebase 函数 onCreate 方法无法在 Firestore 上运行

转载 作者:行者123 更新时间:2023-12-05 04:23:57 26 4
gpt4 key购买 nike

我正在尝试获取用户的用户 ID,然后在 Firebase Functions 的 firestore 上运行 onCreate 函数以获取后台通知,但 onCreate 函数没有运行。该函数显示其已执行和完成。

import { https, firestore, logger } from "firebase-functions";
import { initializeApp, messaging, firestore as _firestore } from "firebase-admin";

initializeApp();
const fcm = messaging();
const db = _firestore();

export const friendRequest = https.onCall((data, context) => {
const userID = context.auth.uid;
try {
db.collection("users")
.doc(userID)
.collection("tokens")
.doc("token")
.get()
.then((value) => {
const token = value.data().token;
firestore
.document(`users/${userID}/recievedRequests/{request}`)
.onCreate((snapshot) => {
const senderName = snapshot.data().name;
logger.log(
"New Notification to " + token + " ,by :" + senderName
);
const payload = {
notification: {
title: "New Friend Request",
body: `Friend Request from ${senderName}`,
},
};
fcm.sendToDevice(token, payload).then((response) => {
logger.log("Response" + response.successCount);
});
});
});
} catch (error) {
logger.log("Error : " + error);
}
});

这是好友请求功能,我想在用户收到通知时向他发送通知。我的 firebase 日志显示 enter image description here

最佳答案

您在另一个函数中有 onCreate(),因此与 friendRequest 不同,它不会首先部署到 Cloud Functions。您似乎正在尝试通知已收到请求的用户。您可以尝试以下功能:

export const notifyUser = firestore
.document(`users/{userId}/recievedRequests/{request}`)
.onCreate(async (snapshot, context) => {
const userId = context.params.userId;
const senderName = snapshot.data().name;

logger.log("New Notification to " + userId + " ,by :" + senderName);

const payload = {
notification: {
title: "New Friend Request",
body: `Friend Request from ${senderName}`,
},
};

// Get Token of the User
const tokenSnap = await db
.collection("users")
.doc(userId)
.collection("tokens")
.doc("token")
.get();

const token = tokenSnap.data()!.token;

return fcm.sendToDevice(token, payload).then((response) => {
logger.log("Response" + response.successCount);
return null;
});
});

要首先发送请求,您可以简单地在 users/RECEIVER_ID/friendRequests/ 子集合中添加一个文档,这将触发上述函数,该函数将获取接收者 FCM token 和发送通知。不需要 onCall() 函数。

关于node.js - 获取用户 ID 后,Firebase 函数 onCreate 方法无法在 Firestore 上运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73596857/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com