【问题标题】:Extract TImestamp from the result of a Function从函数的结果中提取 TImestamp
【发布时间】:2020-02-07 05:07:54
【问题描述】:

所以我有一个这样的界面:

interface Test {
    // ...
    created_at: Timestamp;
    // ...
}

我从这样的函数返回一个对象:

export const getTest = functions.https.onCall(async (data, context) => {
    if (!context.auth) {
        return null;
    }

    let snap = await admin
                 .firestore()
                 .collection('test')
                 .get();

    return snap.docs.map(r => ({ // Add id to the output
        id: r.id,
        ...r.data()
    })[0];
});

所以我应该在我的应用程序中获取时间戳对象,但这是我在 chrome 控制台中得到的,当我尝试从函数中获取对象时,如下所示:

// Using AngularFireFunctions
let result: Test = await this.fns.httpsCallable<void, Test>('getTest')().toPromise();

这是result.created_at的全部内容:

当我调用result.created_at.toDate() 时,我收到....created_at.toDate is not a function 错误。

我能做些什么来改变这种情况?

这就是我现在所坚持的:

result.created_at = new Date(result.created_at._seconds * 1000);

【问题讨论】:

    标签: javascript typescript firebase google-cloud-firestore google-cloud-functions


    【解决方案1】:

    看起来您希望可调用函数保留从它返回的对象的数据类型。这不是它的工作原理。该函数会将传递的对象序列化为 JSON,丢失所有对象类型信息,包括 Timestamp 类型。 Timestamp 正在使用其内部表示进行序列化,这就是您在日志输出中看到的内容。我不会编写依赖于此的代码,因为它显然使用了隐藏的实现细节。

    您可能应该做的是将 Timestamp 转换为普通的 JavaScript 对象,并在返回的结果中使用它。然后,在客户端,您需要编写代码来了解您选择如何表示该时间戳。这是一项额外的工作,但它使客户端不知道那些私有的实现细节。

    我建议将 Timestamp 的秒和纳秒部分放入一个普通的旧对象中,替换现有的 Timestamp 字段,然后使用 Timestamp constructor 将该对象转换回客户端上的 Timestamp,它将秒和 nanos 组件作为论据。

    【讨论】:

    • 好的我已经认为手动转换是没有办法的。太糟糕了。但感谢您的时间和回答!
    • 你遇到的很常见。我建议为 Timestamp 类型提交一个功能请求,以获得一个 toJSON 方法,该方法可以在没有实现细节的情况下正确序列化它。例如,它可能只有一个没有下划线的普通秒和纳秒字段。然后,Timestamp 类可能还应该提供一个 fromJSON 方法来从对象创建一个新的 Timestamp 对象。这样可以缓解一些困难。 support.google.com/firebase/contact/support
    • 好主意,会这样做的!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-27
    • 2013-09-12
    • 1970-01-01
    • 2014-11-09
    • 2019-07-13
    • 1970-01-01
    相关资源
    最近更新 更多