Thomas D. Frøysa
Thomas D. Frøysa

Reputation: 698

Cloud Firestore REST API - Add server timestamp

I'm using an Arduino with an ESP8266-01 module to upload a value to a Cloud Firestore database using the createDocument API with the following payload:

{
    "fields": {
        "distance": {
            "integerValue": "555"
        }
    }
}

I do a POST-request to a route like this:

https://firestore.googleapis.com/v1beta1/projects/<MY_PROJECT>/databases/(default)/documents/<SOME_COLLECTION>?key=MY_VERY_SECRET_KEY

That all works, but I would like to add the server timestamp as well. I've found a few answers here on stackoverflow, but I have not been able to make any of them work.

How can I add the server timestamp to the created document? What I want is for the following to be created:

{
    "fields": {
        "distance": {
            "integerValue": "555"
        },
        "timestamp" : {
            "DATETIME": SERVER_TIMESTAMP
        }
    }
}

Any help appreciated.

Upvotes: 1

Views: 1698

Answers (1)

Thomas D. Fr&#248;ysa
Thomas D. Fr&#248;ysa

Reputation: 698

What I ended up doing in the end was the following:

A POST request to a route like this:

https://firestore.googleapis.com/v1beta1/projects/<MY_PROJECT>/databases/(default)/documents:commit?&key=<MY_VERY_SECRET_KEY>

With the following payload:

{
    "writes": [
        {
            "update": {
                "name": "projects/<MY_PROJECT>/databases/(default)/documents/<COLLECTION_ID>/<DOCUMENT_ID>",
                "fields": {
                    "distance": {
                        "integerValue": "555"
                    }
                }
            }
        },
        {
            "transform": {
                "document": "projects/<MY_PROJECT>/databases/(default)/documents/<COLLECTION_ID>/<DOCUMENT_ID>",
                "fieldTransforms": [
                    {
                        "fieldPath": "servertime",
                        "setToServerValue": "REQUEST_TIME"
                    }
                ]
            }
        }
    ]
}

Where I generate a new DOCUMENT_ID (e.g. a GUID) instead of having cloud firestore generate one for me.

Upvotes: 6

Related Questions