Skip to content

Instantly share code, notes, and snippets.

@sekky0905
Last active February 24, 2018 05:06
Show Gist options
  • Save sekky0905/67e8bbb9ace966cb49e9c050a16f10e7 to your computer and use it in GitHub Desktop.
Save sekky0905/67e8bbb9ace966cb49e9c050a16f10e7 to your computer and use it in GitHub Desktop.
GAE/GoのDatastoreにおけるEntityとPropertiesとPropertyLoadSaverのお話 ref: https://qiita.com/Sekky0905/items/0a4c981ce5dbd0646226
type Property struct {
Name string
Value interface{}
NoIndex bool
Multiple bool
}
type PropertyList []Property
func (l *PropertyList) Load(p []Property) error
func (l *PropertyList) Save() ([]Property, error)
type PropertyLoadSaver interface {
Load([]Property) error
Save() ([]Property, error)
}
func LoadStruct(dst interface{}, p []Property) error
func SaveStruct(src interface{}) ([]Property, error)
type User struct {
ID string
Name string
Address string
Age int
UpdatedAt time.Time `json:"updatedAt"`
}
// Datastore packageがEntityの中身をGetする際には、Loadメソッドを呼びだす。
// []Property(PropertyのSlice)を*PropertyListにロードする。 lを最初に空にするようなことはしない。
func (u *User) Load(ps []datastore.Property) error {
// LoadStructは、第二引数のdatastore.Propertyのslice(property)から
// dst(構造体のポインタ)にロードする
err := datastore.LoadStruct(u, ps)
if fmerr, ok := err.(*datastore.ErrFieldMismatch); ok && fmerr != nil && fmerr.Reason == "no such struct field" {
} else if err != nil {
return err
}
return nil
}
// Datastore packageがEntityの中身をPutする際にはSaveを呼び出す。
// 全てのPropertyをsliceかPropertiesとして、保存する
func (u *User) Save() ([]datastore.Property, error) {
// 第一引数のPropertyをSliceにして、それを返す
// 引数は、構造体のポインタでないといけない
pr, err := datastore.SaveStruct(u)
if err != nil {
return nil, err
}
return pr, nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment