LoginSignup
0
0

More than 5 years have passed since last update.

datastore + Goでメタデータを取得する

Last updated at Posted at 2018-09-12

GAE/Goにてdatastoreのメタデータを取得する場合はdatastore.Kinds等を利用できますが、それを使わない場合の取得方法についてまとめたメモです。
※公式ドキュメントはこちら

取得できるメタデータ

  • Namespace
  • Kind
  • Property

Namespace

func Namespaces(ctx context.Context, client *datastore.Client) ([]string, error) {
    q := datastore.NewQuery("__namespace__").KeysOnly()
    keys, err := client.GetAll(ctx, q, nil)
    if err != nil {
        return nil, err
    }
    namespaces := make([]string, 0, len(keys))
    for _, namespace := range keys {
        namespaces = append(namespaces, namespace.Name)
    }
    return namespaces, nil
}

Kind

func Kinds(ctx context.Context, client *datastore.Client) ([]string, error) {
    q := datastore.NewQuery("__kind__").KeysOnly()
    keys, err := client.GetAll(ctx, q, nil)
    if err != nil {
        return nil, err
    }
    kinds := make([]string, 0, len(keys))
    for _, kind := range keys {
        kinds = append(kinds, kind.Name)
    }
    return kinds, nil
}

Property

指定したkindのpropertyとrepresentationをmapで返す

func KindsProperties(ctx context.Context, client *datastore.Client) (map[string][]string, error) {
    kindKey := datastore.NameKey("__kind__", "Task", nil)
    query := datastore.NewQuery("__property__").Ancestor(kindKey)

    var props []struct {
        Repr []string `datastore:"property_representation"`
    }

    keys, err := client.GetAll(ctx, query, &props)
    if err != nil {
        return nil, err
    }
    propMap := map[string][]string{}
    for i, p := range props {
        propMap[keys[i].Name] = p.Repr
    }
    return propMap, nil
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0