Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting a datastore entity into an interface in Go

I have a couple of datastore Kinds that have the same field Id. Is it possible to create one generic function that can get me this value? Something similar to this?

var i interface{}
err = datastore.Get(c, key, &i)
v := reflect.ValueOf(i)
id := v.FieldByName("Id").String()

The above code, as it is, gives me a "datastore: invalid entity type" error.

like image 626
sathishvj Avatar asked Feb 20 '23 06:02

sathishvj


1 Answers

var i interface{} isn't of any concrete type. The appengine datastore requires a concrete type to deserialize the data into since it uses reflection. It looks like from the documentation that missing fields or fields of a different type than the data was stored from will cause an error to be returned as well so you can't create a struct with just the ID field defined.

Even so it's possible you could work something out using a custom type that implements the PropertyLoadSaver interface like so:

type IdField struct {
  Id string
}

function (f *IdField) Load(ch <-chan Property) error {
  for p := range ch {
    if p.Name == "Id" {
      f.Id = p.Value.(string)
    }
  }
  return nil
}

function (f *IdField) Save(ch chan<- Property) error {
   return fmt.Errorf("Not implemented")
}

var i = &IdField{}
err := datastore.Get(c, key, i)
id := i.Id

It's probably not as concise as you were hoping but it's a little more typesafe doesn't require reflection and illustrates the general approach you could use to get partial data out of the datastore.

like image 83
Jeremy Wall Avatar answered Feb 26 '23 22:02

Jeremy Wall