尝试通过 Firebase Cloud 函数将 DateTime 对象发送到 Firestore

Lab*_*Lab 0 firebase flutter google-cloud-functions google-cloud-firestore

通过将 DateTime 对象从应用程序直接发送到 Firebase,会自动转换为 TimeStamp 格式。但是,如果我通过云函数发送相同的对象,我将收到以下错误:

Invalid argument: Instance of 'DateTime'
Run Code Online (Sandbox Code Playgroud)

我尝试使用该toString()方法传递对象并通过运行 Date.parse 进行后端转换Date.parse(data["birth_date"])。但在 Firestore 上,数据记录为数字而不是时间戳。

颤振代码:

//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});
Run Code Online (Sandbox Code Playgroud)

服务器端代码:

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"]),
      ...
    });
  });
Run Code Online (Sandbox Code Playgroud)

如何使用云函数将 DateTime 对象转换为 TimeStamp ?

Dou*_*son 6

Cloud Functions 客户端 SDK 对从平台日期类型到 Firestore 时间戳的转换一无所知。您必须自己找到一种方法来做到这一点,仅传递函数 SDK 可以理解的有效类型(例如数字和字符串)。

一种方法是将 DateTime 转换为数字(通常是自纪元以来的毫秒数),并将该数字作为参数发送给函数。然后,在该函数中,将该数字转换为 JavaScript Date 对象并将其提供给 Firestore,Firestore 会将其转换为时间戳类型字段。