0

enter image description here

I have this structure in Firebase DB above

Case: When a user sends a message to another user, newMessage field is updated -true- in customers/id/chats/chatid

Then what I am trying to do is fetching last message from messages/chatid via the chatid I am getting from customers/id/chats/chatid

Problem: I do get the update and data on customers and sending notification but I need that last message, Dont know how to do that No JavaScript experience at all. Sample Chat id which I get on customers _path: '/customers/m6QNo7w8X8PjnBzUv3EgQiTQUD12', _data: { chats: { '-LCPNG9rLzAR5OSfrclG': [Object] },

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);


exports.sendNotif = functions.database.ref('/customers/{id}/chats/{id}/').onUpdate((event) => {
    
    const user = event.data.val();
    console.log('Event data: ', event.data);
  
    //HERE I WANT TO USE THAT CHAT ID TO FETCH MESSAGE in MESSAGES.
    // Get last message and send notification.
    // This works when newMessage field is updated.
    // However I neeed the message content from another table.
    
  
    var myoptions = {
      priority: "high",
      timeToLive: 60 * 60 * 24
    };
    
    // Notification data which supposed to be filled via last message. 
    const notifData = {
        "notification":
        {
          "body" : "Great Match!",
          "title" : "Portugal vs. Denmark",
          "sound": "default"
        } 
    }
    

  admin.messaging().sendToDevice(user.fcm.token, notifData, myoptions)
  .then(function(response) {
    console.log('Successfully sent message:', response);
  })
  .catch(function(error) {
    console.log('Error sending message:', error);
  });
  
    return ""
});

3 Answers 3

2

Do as follows. See comments within the code and remarks at the end.

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);

exports.sendNotif = functions.database.ref('/customers/{id}/chats/{chatId}').onUpdate((change, context) => {

    //const afterData = change.after.val();  //I don't think you need this data (i.e. newMessage: true)
    const chatId = context.params.chatId; //the value of {chatId} in  '/customers/{id}/chats/{chatId}/' that you passed as parameter of the ref

    //You query the database at the messages/chatID location and return the promise returned by the once() method        
    return admin.database().ref('/messages/' + chatId).once('value').then(snapshot => {

        //You get here the result of the query to messagges/chatId in the DataSnapshot
        const messageContent = snapshot.val().lastMessage;


        var myoptions = {
           priority: "high",
           timeToLive: 60 * 60 * 24
        };

        // Notification data which supposed to be filled via last message. 
       const notifData = {
        "notification":
        {
          "body" : messageContent,  //I guess you want to use the message content here??
          "title" : "Portugal vs. Denmark",
          "sound": "default"
        } 
       };


       return admin.messaging().sendToDevice(user.fcm.token, notifData, myoptions);
  )
  .catch(function(error) {
        console.log('Error sending message:', error);
  });

});

Note that I have changed the code from

exports.sendNotif = functions.database.ref('/customers/{id}/chats/{id}/').onUpdate((event) => {

to

exports.sendNotif = functions.database.ref('/customers/{id}/chats/{chatId}/').onUpdate((change, context) => {

The latter is the new syntax for Cloud Functions v1.+ which have been released some weeks ago.

You should update your Cloud Function version, as follows:

npm install firebase-functions@latest --save
npm install [email protected] --save

See this documentation item for more info: https://firebase.google.com/docs/functions/beta-v1-diff#realtime-database

Sign up to request clarification or add additional context in comments.

1 Comment

Did work beautifully, I only did change some syntax errors.
1

In order to get the last message, you would have to store some kind of a timestamp (for example using Date.now() in Javascript) in your Firebase database.


Then you would get all the related messages, sort them using sort() function and use just the most recent one

or

you can use combination of three Firebase query functions: equalTo, orderByChild and limitToFirst.

Comments

0

The fact that you are successfully updating the "customers/uid/chats/chat" branch says that you have the chat id/uid. All you do is fetch the "messages/chat" and read it. Since you have the chat id, a .Promise.all approach works here. Something like:

    var promises = [writeChat(),readChat()];

    Promise.all(promises).then(function (result) {
        chat = result[1]; //result[1].val()
    }).catch(function (error) {
        console.error("Error adding document: ", error);
    });

    function readChat() {
        return new Promise(function (resolve, reject) {
          var userId = firebase.auth().currentUser.uid;
          return firebase.database().ref('/users/' + userId).once('value').then(function(snap) {
             resolve (snap)
             // ...
          }).catch(function (error) {
            reject(error);
          });
       });
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.