-
Notifications
You must be signed in to change notification settings - Fork 3
/
key_resolver.go
53 lines (44 loc) · 1.13 KB
/
key_resolver.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package db
import (
"appengine"
"appengine/datastore"
)
type KeyResolver struct {
context appengine.Context
}
// NewKeyResolver creates a new instance of *KeyResolver
func NewKeyResolver(c appengine.Context) *KeyResolver {
return &KeyResolver{
context: c,
}
}
// Resolve resolves the datastore key for the given entity
// by either assembling it based on the structs tags
// or by creating an auto generated key in case no tags are
// provided
//
// ErrMissingStringId is returned in case a string field
// is tagged with db:"id" and is empty
//
// ErrMissingIntId is returned in case an int field
// is tagged with db:"id" and is 0
func (this *KeyResolver) Resolve(e Entity) (*Metadata, error) {
metadata := &Metadata{}
if err := NewKeyResolverExtractorChain(metadata).ExtractFrom(e); err != nil {
return nil, err
}
if metadata.IntID != 0 && metadata.StringID != "" {
return nil, ErrMultipleIdFields
}
e.SetKey(datastore.NewKey(
this.context,
metadata.Kind,
metadata.StringID,
metadata.IntID,
metadata.Parent,
))
if metadata.CacheStringID == "" {
metadata.CacheStringID = e.StringId()
}
return metadata, nil
}