forked from rancher/rancher
/
prefix_type_store.go
80 lines (67 loc) · 2.47 KB
/
prefix_type_store.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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package workload
import (
"strings"
"github.com/rancher/norman/types"
"github.com/rancher/norman/types/convert"
"github.com/rancher/norman/types/definition"
)
type PrefixTypeStore struct {
Store types.Store
}
func (p *PrefixTypeStore) Context() types.StorageContext {
return p.Store.Context()
}
func (p *PrefixTypeStore) ByID(apiContext *types.APIContext, schema *types.Schema, id string) (map[string]interface{}, error) {
_, shortID := splitTypeAndID(id)
data, err := p.Store.ByID(apiContext, schema, shortID)
return addTypeToID(data), err
}
func (p *PrefixTypeStore) List(apiContext *types.APIContext, schema *types.Schema, opt *types.QueryOptions) ([]map[string]interface{}, error) {
data, err := p.Store.List(apiContext, schema, opt)
return addListTypeToID(data), err
}
func (p *PrefixTypeStore) Watch(apiContext *types.APIContext, schema *types.Schema, opt *types.QueryOptions) (chan map[string]interface{}, error) {
c, err := p.Store.Watch(apiContext, schema, opt)
if err != nil {
return nil, err
}
return convert.Chan(c, func(data map[string]interface{}) map[string]interface{} {
return addTypeToID(data)
}), nil
}
func (p *PrefixTypeStore) Create(apiContext *types.APIContext, schema *types.Schema, data map[string]interface{}) (map[string]interface{}, error) {
data, err := p.Store.Create(apiContext, schema, data)
return addTypeToID(data), err
}
func (p *PrefixTypeStore) Update(apiContext *types.APIContext, schema *types.Schema, data map[string]interface{}, id string) (map[string]interface{}, error) {
_, shortID := splitTypeAndID(id)
data, err := p.Store.Update(apiContext, schema, data, shortID)
return addTypeToID(data), err
}
func (p *PrefixTypeStore) Delete(apiContext *types.APIContext, schema *types.Schema, id string) (map[string]interface{}, error) {
_, shortID := splitTypeAndID(id)
return p.Store.Delete(apiContext, schema, shortID)
}
func splitTypeAndID(id string) (string, string) {
parts := strings.SplitN(id, ":", 2)
if len(parts) < 2 {
// Must conform
return "", ""
}
return parts[0], parts[1]
}
func addTypeToID(data map[string]interface{}) map[string]interface{} {
typeName := definition.GetType(data)
id, _ := data["id"].(string)
if typeName != "" && id != "" {
data["id"] = strings.ToLower(typeName) + ":" + id
}
return data
}
func addListTypeToID(data []map[string]interface{}) []map[string]interface{} {
var result []map[string]interface{}
for _, item := range data {
result = append(result, addTypeToID(item))
}
return result
}