exilonX
exilonX

Reputation: 1761

Handling timestamp returned from cloud function query in dart

I am using flutter, firestore and google cloud function to build a mobile app.

On the one hand,some of my firestore queries are executed in the client side in dart code something like this:

Firestore.instance.collection(Collections.cars)
          .where('free', isEqualTo: free)
          .getDocuments();

Now this returns a list of Documents and if I have a timestamp field in that document I can call document.timestamp.toDate() - in order to convert the Firestore timestamp to a dart DateTime

On the other hand if I do the exact the same in my cloud function and return the result and then I use that result in dart code my timestamp will be of type HashMap and contain two fields _seconds and _nanoseconds and I cannot call .toDate() on it to convert it to a DateTime in dart!

I understand that just from returning the result of the query from a cloud function I'm missing some serializing steps to have the same result as from the normal query, but what I'm wondering is what should I do to have the same behavior?

So can I do something in my nodejs code in cloud function to return the timestamp in a more friendly way, making it easier to convert to DateTime?

I could iterate through the result and convert the timestamp to nodejs Date but I don't think it's the best idea.

Upvotes: 0

Views: 255

Answers (1)

Karanveer Singh
Karanveer Singh

Reputation: 1031

I was able to solve this. I had some methods defined for serializing and deserializing data. I put the following code, where it was needed:

     if (value is Map && value.containsKey("_seconds")) {
        value = Timestamp(value["_seconds"], value["_nanoseconds"]);
        value = value.toDate();
      }
      if (value is Map && value.containsKey("_latitude")) {
        final newPoint = GeoPoint(double.parse(value["_latitude"].toString()),
            double.parse(value["_longitude"].toString()));
        value = newPoint.toLatLng();
      }

Just check where this code is needed.

Upvotes: -1

Related Questions