Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert server timestamp in Firestore document using REST?

I want to insert a document using a REST call to Firestore createDocument method. One of the fields is a timestamp field that should be set on the server. With Android SDK it's as simple as annotating a Date field with @ServerTimestamp and keeping it null — now how do I do it in REST?

{
  "fields": {
    "timezoneId": {
      "stringValue": "Europe\/London"
    },
    "city": {
      "stringValue": "London"
    },
    "timestamp": {
      "timestampValue": "???"
    }
  }
}

I tried using null, 0, empty string, timestamp — everything fails with an error requiring the standard RFC3339 format (e.g. 2018-01-31T13:50:30.325631Z). Is there any placeholder value I can use, or any way to obtain that timestamp?

like image 670
Actine Avatar asked Feb 04 '18 16:02

Actine


People also ask

How do I change firestore to timestamp?

To convert a Firestore Timestamp into a Javascript date, just call . toDate() on the Timestamp.

How do I save a timestamp on firestore?

If you want to use server generated value which would be better so you don't depend on device time, use this: Map<String, dynamic> data = { 'name': userName, 'userUID': userUIDglobal, 'time': FieldValue. serverTimestamp(), }; Firestore.

What is the format of firestore timestamp?

Date and time in the Firestore are saved in their proprietary date format — called Timestamp. Firestore timestamp is just a simple object with two properties — seconds and nanoseconds, which apparently has some advantages over “classic” date format.


1 Answers

The Android SDK doesn't execute a createDocument request when creating the document. Instead it uses the write request to issue an update and a transform request at the same time. If you are wanting to only use createDocument, then the answer is no.

Your payload would look something like this:

{
  "writes": [
    {
      "update": {
        "name": "projects/{projectId}/databases/{databaseId}/documents/{document_path}",
        "fields": {
          "timezoneId": {
            "stringValue": "Europe\/London"
          },
          "city": {
            "stringValue": "London"
          }
        }
      },
      // ensure the document doesn't exist
      "currentDocument": {
        "exists": false
      }
    },
    {
      "transform": {
        "document": "projects/{projectId}/databases/{databaseId}/documents/{document_path}",
        "fieldTransforms": [
          {
            "fieldPath": "timestamp",
            "setToServerValue": "REQUEST_TIME"
          }
        ]
      }
    }
  ]
}

The only downside to adding documents this way is you would need to generate the Document ID yourself (the SDK's generate them). I hope this helps.

like image 54
Bryan Massoth Avatar answered Oct 20 '22 16:10

Bryan Massoth