Last active
February 17, 2020 11:04
-
-
Save henrahmagix/8087aff39246ebe48fd247faddcca627 to your computer and use it in GitHub Desktop.
How to get any data from Google Datastore as an untyped map
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
type DynamicEntity map[string]interface{} | |
func (d *DynamicEntity) Load(props []datastore.Property) error { | |
loadMap(*d, props) | |
return nil | |
} | |
func loadMap(m map[string]interface{}, props []datastore.Property) { | |
for _, prop := range props { | |
if nested, ok := prop.Value.(*datastore.Entity); ok { | |
mm := make(map[string]interface{}) | |
loadMap(mm, nested.Properties) | |
m[prop.Name] = mm | |
} else if nestedArray, ok := prop.Value.([]interface{}); ok { | |
arr := make([]interface{}, len(nestedArray)) | |
for i, nested := range nestedArray { | |
mm := make(map[string]interface{}) | |
loadMap(mm, nested.(*datastore.Entity).Properties) | |
arr[i] = mm | |
} | |
m[prop.Name] = arr | |
} else { | |
m[prop.Name] = prop.Value | |
} | |
} | |
} | |
func (d *DynamicEntity) Save() ([]datastore.Property, error) { | |
return nil, nil | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"context" | |
"fmt" | |
"cloud.google.com/go/datastore" | |
) | |
func main() { | |
ctx := context.Background() | |
ds, err := datastore.NewClient(ctx, "my-project-id") | |
handleErr(err) | |
myEntityMap := make(DynamicEntity) | |
err = ds.Get(ctx, datastore.IDKey("MyEntity", 1234, nil), &myEntityMap) | |
fmt.Printf("myEntityMap: %+v\n", myEntityMap) | |
myField := myEntityMap["MyField"].(string) | |
fmt.Println("MyField", myField) | |
myNestedField := myEntityMap["NestedEntity"].(map[string]interface{})["NestedField"].(string) | |
fmt.Println("NestedEntity.NestedField", myNestedField) | |
} | |
func handleErr(err error) { | |
if err != nil { | |
panic(err) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment