For some reason, when I call my sendTheMessage
function, my device (not simulator) does not receive the notification if I retrieve the token from Firestore. However, when I uncomment the part const tok = … which sets the token manually and pass tok into my function, my device (not simulator) receives the notification. How can I make it so that I can get one (and eventually more than one) token from Firestore, then send the message using such token(s)?
const admin = require("firebase-admin");
const { onSchedule } = require("firebase-functions/v2/scheduler");
const { logger } = require("firebase-functions");
const { getFirestore } = require("firebase-admin/firestore");
admin.initializeApp();
exports.checkforsmsnotifs3 = onSchedule("*/5 * * * *", async (event) => {
const db = getFirestore();
const allDocsRef = db.collection("dates");
const snapshot = await allDocsRef.where("checkedIn", "==", false).get();
// TODO: get the token for the correct user
// const tok = "fUPMs-9eB0MTgW6V6mzzqf:APA91bF9a2iSaa_"+
// "d4xECQIYT6HXprjY1ZBP6Bj8Xt0tH12GH3Pp1jQai-Qrbqxowp"+
// "-1UDe6nvUUfWO8CSm10xO1G7n"+
// "ppsCnPGFYO4cKlg9FehscrJc84cNUTqSz1oetPKNVneWnFOtVJ";
// Send notifications to all tokens.
const sendTheMessage = async (tokenParam) => {
const mess = {
notification: {
title: "Your friend is out on a date",
body: "Your friend was supposed to check in on " +
"CheckDate but hasn't yet." +
" You may want to reach out.",
},
token: tokenParam,
};
logger.log("func was called");
logger.log("tokenparam: " + tokenParam);
await admin.messaging().send(mess);
};
snapshot.forEach(async (d) => {
console.log(d.data().toNumber);
const tokRef = db.collection("usersByPhoneNum").doc(d.data().toNumber);
const doc = await tokRef.get();
if (!doc.exists) {
logger.log("No such document!");
} else {
logger.log("Document data:", doc.data().token);
sendTheMessage(doc.data().token);
}
});
});
Tried adding await before sendTheMessage. I suspected it has something to do with asynchrony but haven’t been able to crack it. I know the function is being called because I see the logs. But no notification on my device.