MichaelSolati / geofirestore-js

Location-based querying and filtering using Firebase Firestore.
https://geofirestore.com
MIT License
505 stars 58 forks source link

Unsubscribe from GeoQuery.onSnapshot on document deletion #236

Open Daeon97 opened 2 years ago

Daeon97 commented 2 years ago

Hello Michael πŸ‘‹ I am having issues unsubscribing from a GeoQuery.onSnapshot in an onWrite Cloud Function.

At the topmost of the function body i have a variable listener let listener; Then i have two conditions that checks whether a document was just created or deleted if(!change.before.exists && change.after.exists){ /* checks if document was just created */ } and if(change.before.exists && !change.after.exists){ /* checks if document was just deleted */ }

Inside the first if block i assign ...onSnapshot(...) to listener listener = ...onSnapshot(...); Then inside the second if block i call listener() to unsubscribe from the GeoQuery.onSnapshot subscription made in the first if block as stated in your API docs, in other words, when a document is created the listener is assigned to ...onSnapshot(...). Subsequently when that same document is deleted, i try to unsubscribe from the previous onSnapshot subscription

The problem is i am getting an error

TypeError: listener is not a function

This Cloud Function is in such a way that the first if block will always get called before the second if block (obviously a document can get deleted only after it is created). I don't see what i seem to be doing wrong here. I need some help

I have also posted a more elaborate description of the issue i am facing on Stackoverflow here https://stackoverflow.com/questions/73803324/unsubscribe-from-geoquery-onsnapshot-on-document-deletion

spoxies commented 1 year ago

Creating a listener would not make sense for most Cloud Functions. I assume it does return a Snapshot once but I do not think that Cloud Functions would return a method.

In other words if you create a query without GeoFirestore I would be very surprised if it did return a method to detach. If it does then I have overlooked it and it is 'missing', but I really can't see a realistic use case.

The setup on Stackoverfow currently implies that what you are trying to achieve is; When a new document is created, the cloud function should listen forever for documents that are created near it, until at some point in time that source document is deleted.

Besides the technical limitations (cloud functions have a execution time), that would be very expensive to run as all documents changes would create a new instance that wait until it is deleted. I think you might want to redesign the triggers and add one that observes if a 'category' is changed. Then you might want to use use .collectionGroup('user_documents') to query what nested documents within your structure need to be updated.

So normally you would: