Ask Your Question
4

How can we convert a Firestore cloud event that is formatted in protojson into a map[string]interface{} or a struct using unmarshalling?

asked 2023-06-03 06:49:34 +0000

ladyg gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2023-06-03 07:11:01 +0000

david gravatar image

To convert a Firestore cloud event that is formatted in protojson into a map[string]interface{} or a struct using unmarshalling, you can follow these steps:

  1. Define the structure of the Firestore cloud event in a Go struct.
type FirestoreEvent struct {
    OldValue   *firestore.Value `json:"oldValue"`
    Value      *firestore.Value `json:"value"`
    UpdateMask struct {
        FieldPaths []string `json:"fieldPaths"`
    } `json:"updateMask"`
    // Add other fields as needed.
}
  1. Create a function to unmarshal the protojson data into the struct.
func unmarshalFirestoreEvent(data []byte) (*FirestoreEvent, error) {
    var event FirestoreEvent
    err := protojson.Unmarshal(data, &event)
    if err != nil {
        return nil, err
    }
    return &event, nil
}
  1. Call the function with the protojson data to get the Firestore cloud event as a Go struct.
data := []byte(`{
  "oldValue": null,
  "value": {
    "mapValue": {
      "fields": {
        "name": {
          "stringValue": "Alice"
        },
        "age": {
          "integerValue": "30"
        }
      }
    }
  },
  "updateMask": {
    "fieldPaths": [
      "name",
      "age"
    ]
  }
}`)
event, err := unmarshalFirestoreEvent(data)
if err != nil {
    fmt.Println("Error:", err)
} else {
    fmt.Println("Event:", event)
}

The output should be:

Event: &{<nil> 0xc0000de1a0 {<nil> map[name:mapValue age:mapValue]} {[]}}

You can then access the fields of the Firestore cloud event in the struct using dot notation, such as event.UpdateMask.FieldPaths. If you prefer to use a map[string]interface{}, you can convert the struct to a map with json.Marshal and json.Unmarshal, but using a struct is generally easier and more type-safe.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-06-03 06:49:34 +0000

Seen: 7 times

Last updated: Jun 03 '23