firebase - 当路径中的数据不存在时,如何使用 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
。
检测路径上的数据不存在的最干净/最易读的方法是什么?
我已经搜索了几个小时,但找不到这个问题的明确答案。
解决方案
这是解决此问题的一种方法:
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()
功能。
推荐阅读
- javascript - 覆盖 setTimeout 函数
- c++ - 二维数组教科书示例(Absolute C++,Savitch)中的错误(std::bad_array_new_length)
- c++ - 为什么类的构造函数被调用了四次,而析构函数只在程序即将结束时被调用了两次?
- wordpress - WordPress 禁止
- swift - 在 Xcode 中绘制轨迹
- reactjs - 反应选择控制
- sql - Informatica 表达式转换逻辑更改
- javascript - 同源策略和 CORS
- rust - IDE 和命令行中的 rust 性能
- django - 在 docker 容器中运行 django 开发服务器