Skip to content

Instantly share code, notes, and snippets.

@SilverCory
Created February 22, 2024 12:24
Show Gist options
  • Save SilverCory/454144547a42e16fc5239fef53a90365 to your computer and use it in GitHub Desktop.
Save SilverCory/454144547a42e16fc5239fef53a90365 to your computer and use it in GitHub Desktop.
Firestore Value Flattening and unmarshalling
package firestore_type
import "encoding/json"
type Value struct {
Value interface{}
}
func (v *Value) UnmarshalJSON(data []byte) error {
var fsPayload map[string]interface{}
if err := json.Unmarshal(data, &fsPayload); err != nil {
return err
}
v.Value = DecodeValue(fsPayload)
return nil
}
func (v Value) MarshalJSON() ([]byte, error) {
return json.Marshal(v.Value)
}
func DecodeValue(fsPayload map[string]interface{}) interface{} {
var value interface{}
if fsPayload["integerValue"] != nil {
value = fsPayload["integerValue"].(int64)
} else if fsPayload["doubleValue"] != nil {
value = fsPayload["doubleValue"].(float64)
} else if fsPayload["timestampValue"] != nil {
value = fsPayload["timestampValue"].(string)
} else if fsPayload["stringValue"] != nil {
value = fsPayload["stringValue"].(string)
} else if fsPayload["booleanValue"] != nil {
value = fsPayload["booleanValue"].(bool)
} else if fsPayload["arrayValue"] != nil {
value = DecodeValueArray(fsPayload["arrayValue"].(map[string]interface{}))
} else if fsPayload["mapValue"] != nil {
value = DecodeValueMap(fsPayload["mapValue"].(map[string]interface{}))
} else {
panic("Unrecognized Firestore value type")
}
return value
}
func DecodeValueArray(fsPayload map[string]interface{}) []interface{} {
var values []interface{}
if fsPayload["values"] != nil {
for _, v := range fsPayload["values"].([]interface{}) {
values = append(values, DecodeValue(v.(map[string]interface{})))
}
}
return values
}
func DecodeValueMap(fsPayload map[string]interface{}) map[string]interface{} {
var values = make(map[string]interface{})
if fsPayload["fields"] != nil {
for k, v := range fsPayload["fields"].(map[string]interface{}) {
values[k] = DecodeValue(v.(map[string]interface{}))
}
}
return values
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment