如何解决以原子方式推送新聊天消息并更新 Firebase 实时数据库上的 lastMessage 值
我在此结构中存储聊天消息和聊天元数据:
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()
用于推送新聊天消息,.update()
用于更新 lastMessage 属性。如果多个用户可以同时向特定聊天提交消息,我如何保证 lastMessage 始终等于最后推送的聊天消息?
解决方法
您必须使用 Cloud Functions 的实时数据库触发器才能执行此操作。
// 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});
});
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。