【问题标题】:Firebase Cloud Functions JavaScript - How to get multiple data from different tables in one functionFirebase Cloud Functions JavaScript - 如何在一个函数中从不同的表中获取多个数据
【发布时间】:2018-11-14 00:34:54
【问题描述】:

我在上面的 Firebase DB 中有这个结构

案例:当一个用户向另一个用户发送消息时,customers/id/chats/chatid 中的 newMessage 字段更新-true-

然后我要做的是从 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 ""
});

【问题讨论】:

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


    【解决方案1】:

    请按以下步骤操作。见代码中的cmets和最后的备注。

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

    请注意,我已将代码从

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

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

    后者是几周前发布的 Cloud Functions v1.+ 的新语法。

    您应该更新您的 Cloud Function 版本,如下所示:

    npm install firebase-functions@latest --save
    npm install firebase-admin@5.11.0 --save
    

    有关详细信息,请参阅此文档项:https://firebase.google.com/docs/functions/beta-v1-diff#realtime-database

    【讨论】:

    • 做得很好,我只是改变了一些语法错误。
    • @selcuk 很高兴知道我可以帮助你!顺便说一句,由于我的回答解决了您的问题,您可以接受它,除了您的支持,请参阅meta.stackexchange.com/questions/5234/…Thanks!!
    【解决方案2】:

    为了获得最后一条消息,您必须在 Firebase 数据库中存储某种时间戳(例如在 Javascript 中使用 Date.now())。


    然后你会得到所有相关的消息,使用sort() 函数对它们进行排序并只使用最近的一个

    您可以使用三个 Firebase 查询函数的组合:equalToorderByChildlimitToFirst

    【讨论】:

      【解决方案3】:

      您成功更新“customers/uid/chats/chat”分支的事实表明您拥有聊天 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);
                });
             });
          }
      

      【讨论】:

        猜你喜欢
        • 2018-12-22
        • 2019-10-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-06-29
        • 2018-12-22
        • 2021-07-25
        • 2021-01-09
        相关资源
        最近更新 更多