首页 > 解决方案 > 当路径中的数据不存在时,如何使用 Go Firebase-Admin SDK 检测空结果

问题描述

我正在使用以下代码从 Firebase 实时数据库中获取对象。

type Item struct {
    title string `json:"title"`
}
var item Item
if err := db.NewRef("/items/itemid").Get(ctx, &item); err != nil {
    log.Infof(ctx, "An error occured %v", err.Error())
}
log.Infof(ctx, "Item %v", item)

如果实时数据库中的给定路径中不存在数据,SDK 将不会返回错误,相反,我将在变量中得到一个空结构体item

检测路径上的数据不存在的最干净/最易读的方法是什么?

我已经搜索了几个小时,但找不到这个问题的明确答案。

标签: firebasegofirebase-admin

解决方案


这是解决此问题的一种方法:

type NullableItem struct {
    Item struct {
        Title string `json:"title"`
    }
    IsNull bool
}

func (i *NullableItem) UnmarshalJSON(b []byte) error {
    if string(b) == "null" {
        i.IsNull = true
        return nil
    }

    return json.Unmarshal(b, &i.Item)
}

func TestGetNonExisting(t *testing.T) {
    var i NullableItem
    r := client.NewRef("items/non_existing")
    if err := r.Get(context.Background(), &i); err != nil {
        t.Fatal(err)
    }
    if !i.IsNull {
        t.Errorf("Get() = %v; want IsNull = true", i)
    }
}

作为最佳实践,您还应该实现MarshalJSON()功能。


推荐阅读