【发布时间】: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