samedi 28 novembre 2015

Go: GAE - Datastore and reflection

I'm trying to get rid of some boiler plate code when it comes to checking if an Entity already exists in the Datastore. Since I haven't used the reflect package before I figured this would be a good start.

This is what I came up with - seems to work, are there any obvious no-no's when looking at this snippet of code? Using reflection feels like black magic to me ;)

func exists(c appengine.Context, entity interface{}, field string, value string) (interface{}, error) {
  T := reflect.TypeOf(entity)
  result := reflect.New(reflect.SliceOf(T))
  entityName := T.Elem().Name()

  q := datastore.NewQuery(entityName).Filter(field+" =", value).Limit(1)
  keys, err := q.GetAll(c, result.Interface())
  if err != nil {
    return false, err
  }

  objects := result.Elem().Interface()
  if reflect.ValueOf(objects).Len() == 1 {
    elem := reflect.ValueOf(objects).Index(0).Elem()
    if elem.Kind() != reflect.Struct {
      // TODO: Return appropriate error msg
      return nil, nil
    }

    f := elem.FieldByName("KeyId")
    if f.IsValid() && f.CanSet() {
      f.SetInt(keys[0].IntID())
    }

    return elem.Interface(), nil
  }

  return nil, nil
}





Aucun commentaire:

Enregistrer un commentaire