我正在尝试为群聊应用实施推送通知,该应用的数据库结构粘贴在下面。我想知道如何使用session_users节点仅在用户参与该会话时发送推送通知,以及如何将推送通知发送到多个设备,因为我现在的代码仅使用特定的fcmToken将其发送到我的设备。我应该为用户订阅主题,而这些主题是单独的对话ID吗?这是我第一次使用FCM,因此任何指导将不胜感激。
数据库结构:
conversation_messages {
conversationId: {
message1: {
text: "Hello"
timestamp: 1095819823.123
senderId: aSLKN12KLSDNFK
}
}
},
conversation_users {
conversationId: {
userUID:1
userUID2:1
}
},
users {
userUID: {
fcmToken: "fcmToken"
bio: "bio"
username: "username"
}
}
Index.js代码:现在,此代码将在应用程序内发送的所有消息的推送通知发送到我的设备上。我希望将通知限制为仅用户加入的对话,并防止对我发送的消息进行推送通知。
exports.observeMessages = functions.database.ref('/conversation_messages/{convoId}/{messageId}')
.onCreate((snapshot, context) => {
var convoId = context.params.convoId;
var messageId = context.params.messageId;
var message = snapshot.val();
return admin.database().ref('/conversations/' + convoId).once('value', snapshot => {
var conversation = snapshot.val(); // This gives us the conversation name
return admin.database().ref('/users/' + message.senderId).once('value', snapshot => {
var user = snapshot.val();
var notification = {
notification: {
title: conversation.conversationName,
body: user.username + ": " + message.text
},
token: 'dFlruzs91OM:APA91bHVx-Ga11GZ4fEwGAkrvFIegXPgPkvFrNuYa0U6yL_bdC7urM721SQGdnylpBNYPYMWAFpLbDk7pahe1RUMlQ8rN7iK7EAU89Xg6xpbIcBi6ZbTM7TB8N5zxPwhq0MTdIxIRH61'
}
admin.messaging().send(notification)
.then((response) => {
// Response is a message ID string.
console.log('Successfully sent message:', response);
return response
})
.catch((error) => {
console.log('Error sending message:', error);
throw new Error("Error sending message");
});
})
})
})