我正在开发应用程序的组功能,该组的成员可以将任务添加到他们当前正在处理的组中。因此,添加任务后,我想使用FCM通知所有成员该任务已添加到组中。
编辑:
将任务添加到组的代码在客户端上运行并成功运行。云功能的目的只是向特定成员添加了任务的组的所有成员发送云消息。
这是我对云功能的逻辑:
1号由于可以一次使用forEach()
将任务添加到多个组。
2号我正在获取组中成员的uid,并将其推入数组(uids
)中,以便以后可以检索其fcmTokens。
第三名在forEach
上运行uids
以检索fcmToken。
4.将Cloud消息发送到设备。
但是云功能未按预期执行。
这是我的云功能:
exports.newTaskAdded = functions.https.onCall(async (data, context) => {
const groups = data.groups; //Can be multiple groups hence an array.
const uid = data.uid;
const author = data.author;
const taskId = data.taskId;
const taskTitle = data.taskTitle;
try {
groups.forEach(async group => {
const groupName = group.groupName;
console.log('groupName: ', groupName);
const groupId = groups.groupId;
const membersPromises = [];
membersPromises.push(
admin
.firestore()
.collection('Groups')
.doc(`${groupId}`)
.collection('Members') //Members collection has document for each user with their uid as the document name.
.get(),
);
console.log('memberPromises: ', membersPromises);//Function stops after this.
const membersSnapshot = await Promise.all(membersPromises);
console.log('membersSnapshots', membersSnapshot);
const uids = [];
membersSnapshot.forEach(doc => {
doc.forEach(snap => {
console.log(snap.id);
uids.push(snap.id);
});
});
console.log(uids);
const uidPromises = [];
uids.forEach(uid => {
uidPromises.push(
admin
.firestore()
.collection('Users')
.doc(`${uid}`)
.get(),
);
});
console.log('uidPromises: ', uidPromises);
const tokensSnapshots = await Promise.all(uidPromises);
const notifPromises = [];
tokensSnapshots.forEach(snap => {
console.log(snap.data());
const token = Object.keys(snap.data().fcmTokens);
const payload = {
notification: {
title: `${author} has added a new task to ${groupName}`,
body: `Task Added: ${taskTitle}`,
sound: 'default',
},
};
notifPromises.push(admin.messaging().sendToDevice(token, payload));
});
await Promise.all(notifPromises);
});
} catch (err) {
console.log(err);
}
return {result: 'OK'};
});
您可以看到没有显示错误。
非常感谢您的帮助。谢谢