douce1368 2019-07-15 10:04
浏览 81

Firestore云功能:从事件获取DocumentSnapshot

I'm listening for change events of collection documents, just making a dump what I'm receiving:

func ForwardUserChanged(ctx context.Context, e cloudfn.FirestoreEvent) error {
    raw, err := json.Marshal(e.Value.Fields)
    if err != nil {
        return err
    }
    fmt.Println(string(raw))

    return nil
}

where FirestoreEvent is a custom struct:

// FirestoreEvent is the payload of a Firestore event.
type FirestoreEvent struct {
    OldValue   FirestoreValue `json:"oldValue"`
    Value      FirestoreValue `json:"value"`
    UpdateMask struct {
        FieldPaths []string `json:"fieldPaths"`
    } `json:"updateMask"`
}

type FirestoreValue struct {
    CreateTime time.Time `json:"createTime"`
    Fields     map[string]interface{} `json:"fields"`
    Name       string                 `json:"name"`
    UpdateTime time.Time              `json:"updateTime"`
}

What I want is a simple way of decoding the Fields into my struct, which was saved into the in the same collection before. The thing is that the Fields looks in a pretty complex way and it's not just an easy mapping map[string]interface{} to the struct fields. For example, the Fields looks like this:

{"answers":
  {"mapValue":
    {"fields":
      {"fish-1":
        {"mapValue":
          {"fields":{"option":{"stringValue":"yes"},

but the original struct is

type Report struct {
  Answers map[string]Answer
}

type Answer struct {
  Option string
}

Is there an easy way to de-serialize the map into the struct? Or it should be done "by hand"?

There should be a way to get a DocumentSnapshot from this data. The data from the Firestore look like the protobuf message and it even can be seen in the Document struct from the google.golang.org/genproto/googleapis/firestore/v1.

  • 写回答

1条回答 默认 最新

  • doushichi3678 2019-07-15 13:04
    关注

    It's typical with code that deals with Cloud Firestore for it to manually copy the values from a DocumentSnapshot into a data structure of your own definition.

    The exception to this is with Java code, where the Firestore SDK can use reflection to automatically map field values to and from POJO properties. But not everyone chooses this, as they might need to modify the values going in and out. But I don't think the Firestore SDKs for other languages have this sort of support.

    评论

报告相同问题?

悬赏问题

  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题