简体   繁体   中英

How to structure chat application using Firebase Realtime Database to incorporate user data?

As of right now I am using Firebase Realtime Database to include chat functionality as part of an app I'm working on. The only issue I've seemingly run into is figuring out how to include a user's data (profile, username, birthday, etc.) so that if a user clicks on a chat, they can then seamlessly go to a user's profile page without needing to fetch more data from the backend. Here's the current structure I'm using in Firebase Realtime Database for this:

$chats
  $chatId
    id
    users
      0: some user id
      1: some user id
    lastMessage

$userChats
  $userId
    $chatId: true

$users
  $userId
    user info here

In my case what I would like to know is if it makes more sense to duplicate all the user data for each user into each chat within the users array or if I should just use the referencing userId and pull that data after in a separate request?

Considering I store my users primarily in a separate PostgreSQL database I wonder if I could do a separate query to that database and not even worry about storing the users in the realtime database as well (considering I have to include aggregate info for each user like counters).

If you are always going to be fetching user data alongside a chat, then you should store them together. No need to make more than one call unnecessarily.

However, if you will ever fetch user data and/or conversations separately, I would recommend storing the user data separately and not within the conversation.

Also, if you really want an "immediate" feel (beyond the already "realtime" database performance), you could also fetch the user data in the background as soon as a particular chat is opened. That way, if the user taps to view a profile, it'll have already been fetched and will give that "instantaneous" experience you are looking for.

Plus, you have to remember that Realtime Database charges on the amount of data being transferred, no matter how many calls it takes (as opposed to Firestore which charges on the number of queries), so storing it separately does not increase billing at all compared to one query, and actually saves money in the cases where you don't need both data sets.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM