Background
I'm trying to build a simple SMS messaging app that has two trees stored at the root level: numbers
and messages
– and a two-way relationship between them using indices.
I want to be able to quickly fetch the message history for a particular number, send new messages to new numbers, and send new messages to existing numbers, rendering the sent & received messages in real time.
My data structure looks like this:
{
"messages" : {
"-KGZyhbh9sGsizizVyyq" : {
"5551234" : true,
"body" : "Foo"
},
"-KGZykRFPtdWY2fWb62u" : {
"555000" : true,
"body" : "Bar"
}
},
"numbers" : {
"555000" : {
"messages" : {
"-KGZykRFPtdWY2fWb62u" : true
}
},
"5551234" : {
"messages" : {
"-KGZyhbh9sGsizizVyyq" : true
}
}
}
}
When a new message is sent to a number, the message is added under messages
and Firebase returns a unique ID which I then use to store as a key under numbers/:number/messages
.
This is what I currently have for reading the data back:
var ref = new Firebase('https://FIREBASE-APP.firebaseio.com/');
function fetchMessages(number) {
var numberMessagesRef = ref.child('numbers/' + number + '/messages');
numberMessagesRef.on('child_added', function(snap) {
ref.child('messages/' + snap.key()).once('value', function(message) {
displayMessage(message.val()); // Prepends an <li> in the DOM
});
});
}
$('#number').focusout(function() {
var number = $(this).val();
fetchMessages(number);
});
Questions
- Is this data structure the correct way to structure data in Firebase?
- Am I using indices correctly?
- This seems like it might be really slow to fetch the message history (potentially hundreds of messages) for a number. How do I further optimise?