Problem:
I got a question to onSnapshot and cloud functions behaviour.
If I use onSnapshot, as far as I understand, it does most locally and then updates with the cloud every like 1 sec with a hook.
But I have a cloud function functions.firestore.document(…).onUpdate and this one will be called every time of those update hooks if I have like a text field. The function itself is there to check if a type field (typeA,typeB) has been changed, and if so it does some stuff in other collections.
can I trigger the function somehow manually, like when the subsription is unsubsribed for example, that would be the best? but then I cant compare using the snap.before/after functionality in the cloud functions?
what would be a good way to handle this?
Here is my cloud function, it updates the parent document if the type field is changed in the updated document. And I don’t want to have tons of invocations on OnSnapshot updates
export const incrementCountsOnUpdate = functions.firestore
.document('parent/{parentId}/chiild/{chiildId}')
.onUpdate(async (snap, context) => {
const beforeType = snap.before.data().type
const afterType = snap.after.data().type
if (beforeType === afterType) return
const setRef = snap.before.ref.parent.parent
if (setRef) {
await setRef.update({
[getCounter(beforeType)]: FieldValue.increment(-1),
[getCounter(afterType)]: FieldValue.increment(1)
})
}
})
Solution:
can I trigger the function somehow manually, like when the subsription is unsubsribed for example, that would be the best?
No, you can’t trigger it manually.
what would be a good way to handle this?
You can write another HTTP type function and invoke it from your app whenever you want.