1

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 enter image description here

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.