Firestore chat app - build messages home page

622

The common solution is to do what you propose: store a latest_updated timestamp in the document of each "chat room".

That indeed means that you'll need to do two writes instead of one. But on the other hand, you can now determine the correct ordering with by just reading the "chat room" documents, instead of having read individual messages under it.

Note that, while it is certainly possible to do this with Cloud Functions, this can also be done directly from the client. You can even catch the requirement in security rules that a client can only write a new message, if they also set the latest_updated timestamp of the corresponding "chat room" document to the same value as the timestamp of the message, although this will incur the cost of one additional document read for each message you add.

Share:
622
Evan
Author by

Evan

Updated on December 13, 2022

Comments

  • Evan
    Evan over 1 year

    I have a Flutter chat app with Firestore RTDB backend:

    messages (collection)
        message_1 (document)
            chat (collection)
                chat_1 (document)
                chat_2 (document)
            users (array, document field)
                user_id_1 (String)
                user_id_2 (String)
            user_info (map to store user info, like name, avatar etc)
        message_2 (document)
            chat (collection)
                chat_1 (document)
                chat_2 (document)
            users (array, document field)
                user_id_1 (String)
                user_id_2 (String)
            user_info (map to store user info, like name, avatar etc)
    

    I want to create a home page where it shows all the chats a user is involved in, sorted by most recent, just like any normal chat app:

    enter image description here

    I know how to show the chats the user is involved in. Problem is, I don't know how to handle the sorting. There is one simple way to do this: each time a new message is sent, use a cloud function and update a field in the message document called lastSent, then do orderBy('lastSent', descending: true) in your query. The problem is, each time you send a message, you have to do two writes instead of one just to update this field. Is there a better way to handle this?

    Note: My app is not solely a chat app, this is only part of the main app. Imagine a chat functionality similar to Airbnb, so the volume or frequency of chat messages may not be as large as Facebook messenger for example