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
.