Firebase云函数JavaScript - 如何在一个函数中从不同的表中获取多个数据

时间:2018-06-04 15:58:28

标签: javascript firebase firebase-realtime-database google-cloud-functions

enter image description here

我在Firebase DB上面有这个结构

案例:当用户向其他用户发送消息时,newMessage字段会更新-true- in customers / id / chats / chatid

然后我要做的是从messages / chatid中获取最后一条消息 通过我从客户/ id / chats / chatid

获得的chatid

问题:我确实收到客户的更新和数据并发送通知,但我需要最后一条消息,不知道该怎么做 完全没有JavaScript体验。 我获得客户的示例聊天ID _path:'/ customers / m6QNo7w8X8PjnBzUv3EgQiTQUD12',   _数据:    {聊天:{' - LCPNG9rLzAR5OSfrclG ':[对象]},

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 个答案:

答案 0 :(得分: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.

答案 1 :(得分:1)

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 firebase-admin@5.11.0 --save

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

答案 2 :(得分:0)

您正在成功更新" customers / uid / chats / chat" branch说你有聊天ID / uid。您所做的只是获取"消息/聊天"并阅读它。由于您有聊天ID,因此.Promise.all方法适用于此处。类似的东西:

    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);
          });
       });
    }