Lab
Lab

Reputation: 1407

Trying to send DateTime object to Firestore passing by Firebase Cloud functions

By sending a DateTime object directly to Firebase from the application, the conversion into TimeStamp format is done automatically. However if I send the same object through a Cloud Function, I will get the following error:

Invalid argument: Instance of 'DateTime'

I tried using the toString() method to pass the object and do a back-end conversion by running Date.parse Date.parse(data["birth_date"]). But on Firestore the data is recorded as number and not as Timestamp.

Flutter code:

//final DateTime birthDate; -> To show you the type
final HttpsCallable callable =
          CloudFunctions(region: "europe-west3").getHttpsCallable(
        functionName: 'userFunctions-editUser',
      );
      HttpsCallableResult httpsCallableResult =
          await callable.call({"birth_date": birthDate});

Server side code:

exports.addUser = functions
  .region("europe-west3")
  .https.onCall((data, context) => {
    const userUid = data["userUid"];
    const docRef = admin.firestore().doc(`/users_profils/${userUid}`);

    return docRef.set({
      ...
      birth_date: Date.parse(data["birth_date"]),
      ...
    });
  });

How to convert a DateTime object to a TimeStamp using a Cloud Function ?

Upvotes: 0

Views: 1283

Answers (1)

Doug Stevenson
Doug Stevenson

Reputation: 317467

The Cloud Functions client SDK doesn't know anything about the conversions from platform date types to Firestore timestamps. You'll have to find a way to do that yourself, passing only valid types that the functions SDK can understand (such as numbers and strings).

One way to do this would be to convert your DateTime into a number (usually, milliseconds since epoch), and send that number as an argument to the function. Then, in the function, convert that number to a JavaScript Date object and provide that to Firestore, which will convert it into a timestamp type field.

Upvotes: 6

Related Questions