Reputation: 1
I'm writing a Firestore cloud function to detect once my document changes to check it the user was activated and send a PUSH message
The problem is that the function is not running the collection load functions db.collection("usersToken").doc(userId).get();
const {onDocumentUpdated} = require("firebase-functions/v2/firestore");
const {initializeApp} = require("firebase-admin/app");
const {getFirestore} = require("firebase-admin/firestore");
const logger = require("firebase-functions/logger");
const admin = initializeApp();
const db = getFirestore();
exports.sendPushOnStatusActive = onDocumentUpdated("users/{userId}", (event) => {
// Retrieve the current and previous value
const afterData = event.data.after.data();
const previousData = event.data.before.data();
const userId = event.data.after.data().uid;
if (previousData.status === "review" && afterData.status === "active") {
logger.log("User Activated:", userId);
// Fetch the user"s token
const tokenSnapshot = db.collection("usersToken").doc(userId).get();
if (!tokenSnapshot.exists) {
logger.log("User doesn't have push token", userId);
return null;
}
const userToken = tokenSnapshot.data().fcmToken;
logger.log("Active user:", {userId: userId, token: userToken});
// Prepare the push notification message
const message={
token: userToken,
notification: {
title: "Atualização de Status",
body: "Parabéns! Seu cadastro foi aprovado e já estamos contando as corridas que você fez.",
},
};
// Send the push notification
return admin.messaging().send(message).then((response) => {
logger.log("Notificação push enviada:", response);
return null;
}).catch((error) => {
logger.log("Erro ao enviar push:", error);
throw new Error("Failed to send push notification.");
});
}
});
Firebase is triggering the event once I change user document from review to activate. I'm following the cloud function logs and firestore is executing it
I tried already to add IAM permissions to my service account function adding Cloud Datastore User Cloud Functions Developer Cloud Storage for Firebase Admin Eventarc Admin Firebase Admin Firebase Authentication Admin Firebase Rules Admin Service Account User Storage Object Admin
I tried to raise the permissions level and later on my goal is to reduce to the proper ones.
I also add some try/catch but it doesn't give any error executing the db.collection
I started the configuration using firebase cli, with firebase --init and selected my project with my user logged.
Upvotes: 0
Views: 44
Reputation: 830
get()
returns a promise, therefore you should wait for the promise to resolve, as seen from the documentation.
// Fetch the user"s token
const tokenSnapshot = await db.collection("usersToken").doc(userId).get();
Check out this example from the firebase documentation.
Upvotes: 0