I just encountered this piece of firebase doc on firebase.firestore.SnapshotOptions:
serverTimestamps
serverTimestamps: "estimate" | "previous" | "none"If set, controls the return value for server timestamps that have not yet been set to their final value.By specifying
'estimate', pending server timestamps return an estimate based on the local clock. This estimate will differ from the final value and cause these values to change once the server result becomes available.By specifying
'previous', pending timestamps will be ignored and return their previous value instead.If omitted or set to
'none',nullwill be returned by default until the server value becomes available.
And that got me worried, 'cause I'm trying to convert my client generated dates to server timestamps. I thought that whenever a I read a document snapshot that was saved with a serverTimestamp(), I could be 100% that a date would have been set at that point. But from that documentation above, it seems that I cannot make that assumption.
As a general question:
In which situations could I find a serverTimestamp that hasn't been set yet? Is there a common use case where that could be an issue?
Specifically I would like to know about these two cases:
CASE 1
- Saved a document to firestore with a field
createdAt: firebase.firestore.FieldValue.serveTimestamp() - I have a cloud function with a firestore
onWrite | onUpdatetrigger for that specific collection.
When that function runs, is there a possibility that the createdAt: serverTimestamp has not been set yet?
CASE 2
- Saved a document to firestore with a field
createdAt: firebase.firestore.FieldValue.serveTimestamp() - On client I have a listener for that
docI just saved/updated.
When that listener fires with the new docSnapshot data, is there a possibility that the createdAt: serverTimestamp has not been set yet?
UPDATE
Just found this article The secrets of Firestore’s FieldValue.serverTimestamp()
It seems that for the CASE 2 this would only happens for local writes. Given that fact, is it safe to assume that on CASE 1, since it's not a local write, it would never happen on a cloud function that is listening to a firestore trigger?
Firebase docs on Local Changes
Local writes in your app will invoke snapshot listeners immediately. This is because of an important feature called "latency compensation." When you perform a write, your listeners will be notified with the new data before the data is sent to the backend.
Retrieved documents have a metadata.hasPendingWrites property that indicates whether the document has local changes that haven't been written to the backend yet. You can use this property to determine the source of events received by your snapshot listener.