Cloud Function Firestore触发器,文档使用不准确的数字字段



我将在GoLang中实现一个firestore触发器,它将侦听集合上的更改,并将在不同的集合上创建一个新文档。

到目前为止还不错,我在这里看了一下官方文档:https://cloud.google.com/functions/docs/calling/cloud-firestore#event_structure,它给出了一个关于我们如何使用自定义结构(这里表示为MyData)的示例,如下所示:

// FirestoreValue holds Firestore fields.
type FirestoreValue struct {
        CreateTime time.Time `json:"createTime"`
        // Fields is the data for this value. The type depends on the format of your
        // database. Log an interface{} value and inspect the result to see a JSON
        // representation of your database fields.
        Fields     MyData    `json:"fields"`
        Name       string    `json:"name"`
        UpdateTime time.Time `json:"updateTime"`
}
// MyData represents a value from Firestore. The type definition depends on the
// format of your database.
type MyData struct {
        Original struct {
                StringValue string `json:"stringValue"`
        } `json:"original"`
}

这很好。现在更棘手的是如果我们的文档有一个数字而不是字符串,比如:

type MyOtherData struct {
        Original struct {
                DoubleValue float64 `json:"doubleValue"`
        } `json:"original"`
}

一切看起来都很好,事实上它工作,但只有当文档有一个小数部分的数字,如:1.2。然而,如果这个文档碰巧有一个没有小数部分的值,比如:1,那么这个数字解码到MyOtherData为0

编辑:

好,现在我明白为什么它是0,因为事实上,firestore不区分整数和浮点数,这使得对象(在json中):

"fields":{"original":{"doubleValue":3.5}

如果文档的值有小数部分。但附带:

"fields":{"original":{"integerValue":"3"}

如果文档没有小数部分。

有谁知道这应该如何优雅地处理吗?在这种情况下,我希望避免使用接口{}…

Thanks in advance:)

所以,我发现更好的选择是像这样改变我的结构:

type MyOtherData struct {
        Original FirestoreNumber `json:"original"`
}
type FirestoreNumber struct {
    DoubleValue  float64 `json:"doubleValue"`
    IntegerValue int     `json:"integerValue,string"`
}
func (fn *FirestoreNumber) Value() float64 {
    if fn.IntegerValue != 0 {
        return float64(fn.IntegerValue)
    }
    return fn.DoubleValue
}

然后,我不直接访问myOtherData.Original.DoubleValue,而是访问myOtherData.Original.Value()

如果有人知道更好的选择,请分享:)

最新更新