简体   繁体   中英

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

I am trying to get the userID of the user and then running a onCreate function on the firestore in Firebase Functions for background notifications, but the onCreate function doesn't run.The function shows its executed and finished.

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

This is the Friend Request function I want to send notification to user when he receives a notification. My firebase log shows在此处输入图像描述

You have the onCreate() within another function so that's not deployed to Cloud Functions at first place unlike the friendRequest . It seems you are trying to notify a user who has received the request. You can try the following 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;
    });
  });

To send the request at first place, you can simply add the a document in users/RECEIVER_ID/friendRequests/ sub-collection that'll trigger the above function that'll fetch receivers FCM token and send the notification. There's no need of the onCall() function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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