【问题标题】:How to get value inside transaction result Firebase via node js如何通过节点 js 在交易结果 Firebase 中获取价值
【发布时间】:2019-06-01 04:43:31
【问题描述】:

我正在使用 Swift、Firebase 和 Nodejs 构建一个 iOS Messenger 应用程序。

我的目标:
每当用户发送消息并将消息数据(例如 senderId、receiverId、messageText)写入节点(/messages/{pushId}/)内的 Firebase 数据库时,我想使用事务方法将消息计数增加 1 Firebase 向接收者用户提供并显示通知。

到目前为止我取得的进展和我面临的问题:
我已经使用事务方法成功增加了消息计数(totalCount),但我无法在事务结果中获取值(这是函数日志的图像)

我想在快照中获取“value_: 1”(这是增加的消息计数)并将其放入徽章参数中。

exports.observeMessages = functions.database.ref('/messages/{pushId}/')
 .onCreate((snapshot, context) => {

const fromId = snapshot.val().fromId;
const toId = snapshot.val().toId;
const messageText = snapshot.val().messageText;

console.log('User: ', fromId, 'is sending to', toId);

return admin.database().ref('/users/' + toId).once('value').then((snap) => {
  return snap.val();

}).then((recipientId) => {
  return admin.database().ref('/users/' + fromId).once('value').then((snaps) => {
    return snaps.val();

  }).then((senderId) => {
    return admin.database().ref('/user-messages/' + toId + '/totalCount').transaction((current) => {
      return (current || 0) + 1
    }).then((readCount) => {

      console.log('check readCount:', readCount);

      var message = {

       data: {
         fromId: fromId,
         badge: //I want to display the message count here
       },

       apns: {
         payload: {
           aps: {
             alert: {
               title: 'You got a message from ' + senderId.username,
               body: messageText
             },

             "content-available": 1
           }
         }
       },

       token: recipientId.fcmToken
     };

     return admin.messaging().send(message)
     }).then((response) => {
           console.log('Successfully sent message:', response);
           return response;
         })
         .catch((error) => {
           console.log('Error sending message:', error);
           //throw new error('Error sending message:', error);
         })
     })
   })
})

有人知道怎么做吗? 提前致谢。

【问题讨论】:

    标签: javascript swift firebase firebase-realtime-database firebase-cloud-messaging


    【解决方案1】:

    transaction() 的 API 文档表明,来自事务的承诺将接收具有属性 snapshot 的对象,其中包含在事务位置写入的数据的快照。所以:

    admin.database.ref("path/to/count")
    .transaction(current => {
        // do what you want with the value
    })
    .then(result => {
        const count = result.snapshot.val();  // the value of the count written
    })
    

    【讨论】:

    • 谢谢!它就像一个魅力!顺便说一句,我喜欢你在 youtube 上的 Firebase 系列
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-08
    • 2017-04-03
    • 2021-03-02
    • 2021-09-23
    • 1970-01-01
    • 2021-11-23
    相关资源
    最近更新 更多