如果路径中的数据不存在,如何使用Go Firebase-Admin SDK检测空结果

问题描述 投票:0回答:1

我正在使用以下代码从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中最终得到一个空结构。

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

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

firebase go firebase-admin
1个回答
0
投票

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

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()功能。

© www.soinside.com 2019 - 2024. All rights reserved.