Reputation: 115
My firebase function returns a result from the query but it doesn't update if the db changes. How can I update it to return realtime updates? I tried putting an observer in the function but it only fires once.
getCurrentMessage.js // firebase function
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}`)
}
}
the function call
// get current message
axios
.get(`${dir}/getCurrentMessage?location=${location}`)
.then((res) => {
this.setState({
customMessage: res.data,
})
})
.catch((e) => {
console.log(`Error: ${e.message}`)
})
Upvotes: 1
Views: 140
Reputation: 317352
What you're trying to do isn't possible with Cloud Functions. Cloud Functions can only return a single response to the client. It can't send multiple responses, nor can it stream results to the client. Once you call send()
on the response object, the request is terminated and can do nothing else.
If you want the client to receive realtime updates, then it should either query the database directly, or you should use a backend that supports websockets or some other streaming technology.
Upvotes: 2