Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to structure chat with firebase

I'm using Cloud Firestore (NoSQL) to store profile information for users like:

{
  "uid": "abc123",
  "name": "...",
  "friends": [
    "uid": "x234", 
  ]
  ...
}

Now I'm wondering how to structure a direct chat from user to user. I'm thinking of either:

Adding an addional field for each user document like:

"chats": [
 {
    "from": "name",
    "message": "...",
    ...
 },
  ...
]

Or instead of using Firestore for the chat, I consider using Firebase realtime database with a similar structure.

The last approach would have the benefit, that the user-document would not be "bloated" with lots of chat protocols.

I'd need some advice which would structure/implemention would suit this usecase best.

like image 330
Piwo Avatar asked Dec 18 '22 02:12

Piwo


1 Answers

When you start building an app, first you need to think about the database which is most appropriate for it. If you think about Firestore, you need to know that Cloud Firestore's pricing model for applications that perform very large numbers of small reads and writes per second per client could be significantly more expensive than a similarly performing app in the Realtime Database.

There are also are a few differences between these two databases. If you want to go ahead with Firebase Realtime Database you need to know that you cannot query over multiple properties and it usually involves duplication data or client-side filtering, which in some cases is some kind of messy. Realtime Database does not scale automatically while Firestore, does.

Regarding how to structure a database for a chat application, you need to know that there is no perfect structure for doing that. You need to structure your database in a way that allows you to read/write data very easily and in a very efficient way. Firebase official documentation explains how can you structure a database for a chat app. If you want something more complex, please read this post, Structuring your Firebase Data correctly for a Complex App.

For a better understanding, I recommend you as well to take Firebase free courses, Firebase in a Weekend: Android.

So it's up to you to decide which one is better for you.

P.S: If you are interested, I have also explained in one of my tutorials how you can create a Chat App using Cloud Firestore and Kotlin.

like image 96
Alex Mamo Avatar answered Jan 02 '23 23:01

Alex Mamo