繁体   English   中英

Firebase 函数 onCreate 方法在获取用户 ID 后无法在 Firestore 上运行

[英]Firebase Functions onCreate method not working on Firestore after getting the userID

我正在尝试获取用户的用户 ID,然后在 Firebase 的 Firestore 上运行 onCreate function 用于后台通知的功能,但 onCreate ZC1C425268E68385D1AB5074C17A94 不运行 function 显示它的执行和完成。

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

这是朋友请求 function 我想在用户收到通知时向他发送通知。 我的 firebase 日志显示在此处输入图像描述

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

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/子集合中添加一个文档,该文档将触发上述 function,它将获取接收者 FCM 令牌并发送通知。 不需要onCall() function。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM