Reputation: 435
I feel like I'm just missing something silly here because all the examples including codelab show that accessing the event data is straightforward. But I can't get it to work.
I have a straightforward chat/conversation structure that looks like:
conversations/uniqueconversationId/uniquemessageId/
and inside the unique message I store text, user, etc. Every time a new message is posted in the app, I push a new message to the conversation.
In Cloud Functions, I want to know when a new message is posted and send a notification. This is almost 100% the same as the codelab example.
exports.sendNotification = functions.database.ref('/conversations/{conversationId}').onWrite(event => {
const snapshot = event.data;
// Only send a notification when a new message has been created.
if (snapshot.previous.val()) {
return;
}
console.log(snapshot);
...
All the examples show accessing the snapshot value is as simple as
const text = snapshot.val().text;
But that doesn't work for me. When I attempt to access it, it says it is undefined. When I keep the check of snapshot.previous.val() which I pulled straight from codelab, it just returns, even though I'm posting a new message. (And even if I take this out so I can log the snapshot, it still doesn't work.)
When I look in the console, the DeltaSnapshot is huge and contains all the message objects in the conversation. I cannot directly access the new message values as expected.
Here is the chunk of code that writes to the DB (this is from React, BTW). This write works perfectly.
var messageData = {
user: {
_id: user.uid,
name: user.fullName
},
text: messageText,
createdAt:firebase.database.ServerValue.TIMESTAMP,
sentToUser: conversation.recipientUid
};
this.getRef().child('conversations').child(conversation.conversationId).push(messageData)
Here is the JSON for an example message:
{
"-Km9qFcNClX3uQXX51D1" : {
"createdAt" : 1496978098834,
"text" : "Test message sent",
"user" : {
"_id" : "cKFnsNkYSyNXm5duUy",
"name" : "Test User"
}
}
}
Ideally, based on the examples I would expect to be able to just use snapshot.val().text and get "Test message sent."
Any direction you can point me in will be appreciated. Thanks.
Upvotes: 1
Views: 1169
Reputation: 38289
You're triggering on writes one level too high. You want writes to the message ID:
functions.database.ref('/conversations/{conversationId}/{messageId}').onWrite(...)
Then the snapshot will be for the messageData
under messageId
and not the list of all the messages in the conversation.
Upvotes: 3