I am designing a chat app with the help of firebase but I am struck with the database design for the same. I have read the following link provided by firebase structure data for app
My current approach:
"messages" : {
"-Kkiyu4zSKQAzu3MxpGe": {
"recId" : 1994,
"senderId" : 9,
"senderName" : "Alex",
"text" : "Hello",
"time" : "2017-05-22T12:37:41+0530"
},
"-Kkiyw1yVTbR_wDFFiuA" : {
"recId" : 9,
"senderId" : 1994,
"senderName" : "Ted",
"text" : "Hi",
"time" : "2017-05-22T12:37:49+0530"
},
"-KkiywFENy__tCHuuuom" : {
"recId" : 1994,
"senderId" : 9,
"senderName" : "Alex",
"text" : "What's up?",
"time" : "2017-05-22T12:37:50+0530"
},
"-KkiyxDjsUIXBlM0Cn3R" : {
"recId" : 9,
"senderId" : 1994,
"senderName" : "Ted",
"text" : "All good",
"time" : "2017-05-22T12:37:54+0530"
}
similarly, I have user JSON structure and in that structure, I am having 3 types of users which are as follows
1. Branch Manager
2. Delivery boy
3. Admin
"users" : {
"9" : {
"empId" : 9,
"isOnline" : false,
"name" : "Alex",
"userType" : "M"
},
"1994" : {
"branchId" : 9,
"empId" : 1994,
"isOnline" : false,
"name" : "Ted",
"userType" : "D"
},
"25" : {
"empId" : 25,
"isOnline" : false,
"name" : "Tim",
"userType" : "A"
}
}
and my listeners in application are as follows:
sendReference.observe(.childAdded, with: { (snapshot) in
if let data = snapshot.value {
let message = RCMessage(object: data)
message.Id = snapshot.key
let dbManager = RCPersistencyManager()
dbManager.add(message: message)
}
})
receiveReference.observe(.childAdded, with: { (snapshot) in
if let data = snapshot.value {
let message = RCMessage(object: data)
message.Id = snapshot.key
let dbManager = RCPersistencyManager()
dbManager.add(message: message)
dbManager.update(userwithMessage: message)
}
})
i added the listners on the my senderId and my recieverId which i thought was cleaver as i will be recieving messges only that are either send by or directed towards me.
sendReference = companyReference.child("messages").queryOrdered(byChild: "senderId").queryEqual(toValue: Int(RCDataManager.get(stringforKey: "RCUserID")!))
receiveReference = companyReference.child("messages").queryOrdered(byChild: "recId").queryEqual(toValue: Int(RCDataManager.get(stringforKey: "RCUserID")!))
but now the bigger problem arrived i attach these listeners as soon the app is in foreground now the data I receive is every single child created under the following query I do maintain a local database for app but i don't want to get all the children again and again as when the number of children will be more than 200 or say 300 it takes time to sync the database which decreases my app's performance I want to get only the new messages under the queries and I know this design is not good to get that really looking forward to good answers.
Thanks in advance