我将聊天消息和聊天元数据存储在以下结构中:
project
|
-- chats
|
-- 1
|
-- -MFBvnTIQgVKdyFzDMpy
|
-- message: "hello"
|
-- -MEZutiaxOthE-7nDOkA
|
-- message: "how are you?"
|
-- 2
|
-- -MENuu8TjwWrBTkIzue_
|
-- message: "hi"
|
-- -MFBTqEqhR9Dtv3MlMd6
|
-- message: "you good?"
|
-- chatMetadata
|
-- 1
|
-- lastMessage: "how are you?"
|
-- 2
|
-- lastMessage: "you good?"
每当用户向特定聊天提交新的聊天消息时,该聊天的lastMessage属性都应在chatMetadata中更新。该过程包含两个独立的操作:用于推送新聊天消息的.push()
和用于更新lastMessage属性的.update()
。如果多个用户可以同时向特定聊天提交消息,我如何保证lastMessage始终等于上次推送的聊天消息?
您必须使用云功能的实时数据库触发器才能做到这一点。
// Listens for new messages added to /chats/:chatId/ and creates an
// uppercase version of the message to /chatMetadata/:chatId/
exports.updateLastMessage = functions.database.ref('/chats/{chatId}/')
.onCreate((snapshot, context) => {
// Grab the current value of what was written to the Realtime Database.
const original = snapshot.val();
// You must return a Promise when performing asynchronous tasks inside a Functions
// Writing the lastMessage node
return snapshot.ref.parent.parent.child('chatMetadata').child(context.params.chatId).set({lastMessage: original.message});
});