Reputation: 370
I am having an issue with the firebase.firestore.Timestamp class.
I am working on an Angular 6 app with firestore. I have been using Timestamps with no issues for a while, but I am in the process of moving some of my client-side services to cloud functions.
The issue is this:
When I perform a write operation directly from the client side, such as this:
const doc = { startTimestamp: firebase.firestore.Timestamp.fromDate(new Date()) };
firebase.firestore().doc('some_collection/uid).set(doc);
The document gets written correctly to firestore as a Timestamp.
However, when I send doc to a cloud function, then perform the write from the function, it gets written as a map, not a timestamp. Similarly, if I use a JS Date() object instead of a firestore.Timestamp, it gets written correctly from the client side but written as a string from the cloud function.
This makes sense given that the documents is just JSON in the request.body, I guess I was just hoping that firestore would be smart enough to implicitly handle the conversion.
For now, I have a workaround that just manually converts the objects into firestore.Timestamps again in the cloud function, but I am hoping that there is a more effective solution, possibly something buried in the SDK that I have not been able to find.
Has anyone else come across and, ideally, found a solution for this?
I can provide more code samples if needed.
Upvotes: 2
Views: 1660
Reputation: 317808
The behavior you're observing is expected. The Firestore client libraries have a special interpretation of Timestamp type objects, and they get converted to a Timestamp type field in the database when written. However, if you try to serialize a Timestamp objects as JSON, you will just get an object with the timestamp's milliseconds and nanoseconds components. If you want to send these timestamp components to Cloud Functions or some other piece of software, that's fine, but that other piece of software is going to have to reconstitute a real Timestamp object from those parts before writing to Firestore with the Admin SDK or whatever SDK you're using to deal with Firestore.
Upvotes: 2
Reputation: 3406
in your class model, use the
@ServerTimestamp var timestamp: Date? = null
or
@ServerTimestamp Date timestamp = null
You can leave out initializing timestamp from your code, say new Date()
Example:
@IgnoreExtraProperties
data class ProductItem(
var userId: String? = "",
var avgRating: Double = 0.toDouble(),
@ServerTimestamp var timestamp: Date? = null
)
or
public class ProductItem() {
String userId;
Double avgRating;
@ServerTimestamp Date timestamp;
}
Upvotes: 0