我在使用 Firebase 云功能和云消息传递时遇到问题。我可以在日志中看到该函数在需要时运行,但没有发送云消息。(什么也没有发生)我试图在触发该函数时向用户发送通知,但由于某种原因,什么也没有发生,也没有抛出错误.
const functions = require("firebase-functions");
const admin = require("firebase-admin");
admin.initializeApp();
exports.notifySeniorOnTicketAcceptance = functions.firestore
.document("tickets/{ticketId}")
.onUpdate((change, context) => {
const newData = change.after.data();
const previousData = change.before.data();
// Check if the isAccepted field changed from false to true
if (newData.isAccepted === true && previousData.isAccepted !== true) {
const seniorUserId = context.params.ticketId;
return admin.firestore().collection("seniors").doc(seniorUserId).get()
.then((seniorSnapshot) => {
if (seniorSnapshot.exists) {
const seniorData = seniorSnapshot.data();
if (seniorData && seniorData.deviceToken) {
// Send notification to the senior
const message = {
data: {
title: "Ticket Accepted",
body: "Your ticket has been accepted.",
},
token: seniorData.deviceToken,
};
return admin.messaging().send(message);
} else {
console.error("Seniordocument is missing deviceToken field.");
return null;
}
} else {
console.error("Senior document not found.");
return null;
}
})
.catch((error) => {
console.error("Error retrieving senior information:", error);
return null;
});
}
return null;
});
我做了一些更改,可能还有其他原因,但请尝试以下操作并让我们知道
exports.notifySeniorOnTicketAcceptance = functions.firestore
.document("tickets/{ticketId}")
.onUpdate(async (change, context) => {
const newData = change.after.data();
const previousData = change.before.data();
// Check if the isAccepted field changed from false to true
if (newData.isAccepted === true && previousData.isAccepted !== true) {
const seniorUserId = newData.seniorUserId; //<---try by pass the new data not the context.params.ticketId;
return await admin //<-use await
.firestore()
.collection("seniors")
.doc(seniorUserId)
.get()
.then(async (seniorSnapshot) => {
if (seniorSnapshot.exists) {
const seniorData = seniorSnapshot.data();
if (seniorData && seniorData.deviceToken) {
// Send notification to the senior
const message = {
data: {
title: "Ticket Accepted",
body: "Your ticket has been accepted.",
},
token: seniorData.deviceToken,
};
return await admin.messaging().send(message); //<-use await
} else {
console.error("Senior document is missing deviceToken field.");
return null;
}
} else {
console.error("Senior document not found.");
return null;
}
})
.catch((error) => {
console.error("Error retrieving senior information:", error);
return null;
});
}
return null;
});