【问题标题】:How to make Firebase function return realtime snapshot如何使 Firebase 函数返回实时快照
【发布时间】:2021-04-06 02:05:50
【问题描述】:

我的 firebase 函数从查询返回结果,但如果数据库发生变化,它不会更新。如何更新它以返回实时更新?我尝试在函数中放置一个观察者,但它只触发一次。

getCurrentMessage.js // firebase 函数

const admin = require('../variables').admin

module.exports = async (req, res) => {
  const db = admin.firestore()
  const now = new Date()
  const timestampNow = now / 1000
  const location = req.query.location

  try {
    const messagesRef = db.collection('messages')
    const snapshot = await messagesRef
      .where('displayTo', '>=', timestampNow)
      .where('location', '==', location)
      .get()
    if (snapshot.empty) {
      console.log('No matching documents.')
      return res.status(404).send(`No current message found.`)
    }
    snapshot.forEach((doc) => {
      if (doc._fieldsProto.displayFrom.integerValue <= timestampNow) {
        return res.status(200).send(doc) // return 1st to match
      } else {
        return res.status(404).send('No current message found.')
      }
    })
  } catch (e) {
    console.log(`Error: ${e.message}`)
  }
}

函数调用

    // get current message
    axios
      .get(`${dir}/getCurrentMessage?location=${location}`)
      .then((res) => {
        this.setState({
          customMessage: res.data,
        })
      })
      .catch((e) => {
        console.log(`Error: ${e.message}`)
      })

【问题讨论】:

    标签: reactjs firebase google-cloud-firestore google-cloud-functions


    【解决方案1】:

    使用 Cloud Functions 无法实现您想要做的事情。 Cloud Functions 只能向客户端返回单个响应。它不能发送多个响应,也不能将结果流式传输到客户端。一旦你在响应对象上调用send(),请求就会被终止并且不能做任何其他事情。

    如果您希望客户端接收实时更新,那么它应该直接查询数据库,或者您应该使用支持 websockets 或其他一些流技术的后端。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多