问题
In my cloud functions's index.js
file, I have the following function body:
exports.onSuggestionCreated = functions.firestore.document('suggestions/{userId}').onCreate(event => {
return admin.firestore().doc(`places/settings/profile`).get().then(doc => {
[...]
const location = data.location
const ref = admin.database().ref(`suggestion_locations`)
const geoFire = new GeoFire(ref)
var geoQuery = geoFire.query({
center: [location.latitude, location.longitude],
radius: 1.0
})
geoQuery.on("key_entered", function(key, location, distance) {
return sendMessageTo(key, title, body)
})
})
})
This is inside a function that is triggered whenever something is created.
What I would to know is, is the "key_entered" called every time something enters the region delimited by location and radius of GeoFire
even though the cloud function has long been terminated? I got some strange logs that indicate so.
Given the asynchronous nature of GeoFire
, what could I do in this situation?
回答1:
GeoFire relies on keeping active listeners on the geodata that is within range. This does not match with Cloud Functions' run-and-exit paradigm.
The concepts (storing lat+lon in geohashes and running range queries on that) work fine, but you may have to modify the library or pay attention to its implementation details to make it work in your situation.
The best seems to be to return for example all locations that are currently within a given area. This can be done by listening to the key_entered
event (as you already do) and to the ready
event, which fires after the initial key_entered calls have been received.
exports.onSuggestionCreated = functions.firestore.document('suggestions/{userId}').onCreate(event => {
return admin.firestore().doc(`places/settings/profile`).get().then(doc => {
[...]
const location = data.location
return new Promise(function(resolve, reject) {
const ref = admin.database().ref(`suggestion_locations`)
const geoFire = new GeoFire(ref)
var geoQuery = geoFire.query({
center: [location.latitude, location.longitude],
radius: 1.0
})
geoQuery.on("key_entered", function(key, location, distance) {
sendMessageTo(key, title, body)
})
geoQuery.on("ready", function() {
resolve();
});
});
})
})
来源:https://stackoverflow.com/questions/49100433/firebase-geofire-and-cloud-functions-does-end-of-function-means-no-more-liste