-
Notifications
You must be signed in to change notification settings - Fork 329
/
template_marshal.go
104 lines (85 loc) · 1.99 KB
/
template_marshal.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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
package store
import (
"context"
"github.com/cortezaproject/corteza/server/pkg/envoy/resource"
"github.com/cortezaproject/corteza/server/store"
)
func NewTemplateFromResource(res *resource.Template, cfg *EncoderConfig) resourceState {
return &template{
cfg: mergeConfig(cfg, res.Config()),
res: res,
}
}
func (n *template) Prepare(ctx context.Context, pl *payload) (err error) {
// Reset old identifiers
n.res.Res.ID = 0
// Try to get the original template
n.t, err = findTemplateStore(ctx, pl.s, makeGenericFilter(n.res.Identifiers()))
if err != nil {
return err
}
if n.t != nil {
n.res.Res.ID = n.t.ID
}
return nil
}
func (n *template) Encode(ctx context.Context, pl *payload) (err error) {
res := n.res.Res
exists := n.t != nil && n.t.ID > 0
// Determine the ID
if res.ID <= 0 && exists {
res.ID = n.t.ID
}
if res.ID <= 0 {
res.ID = NextID()
}
us, err := resolveUserstamps(ctx, pl.s, pl.state.ParentResources, n.res.Userstamps())
if err != nil {
return err
}
ts := n.res.Timestamps()
if ts != nil {
if ts.CreatedAt != nil {
res.CreatedAt = *ts.CreatedAt.T
} else {
res.CreatedAt = *now()
}
if ts.UpdatedAt != nil {
res.UpdatedAt = ts.UpdatedAt.T
}
if ts.DeletedAt != nil {
res.DeletedAt = ts.DeletedAt.T
}
}
if us != nil {
if us.OwnedBy != nil {
res.OwnerID = us.OwnedBy.UserID
}
}
// Evaluate the resource skip expression
// @todo expand available parameters; similar implementation to compose/types/record@Dict
if skip, err := basicSkipEval(ctx, n.cfg, !exists); err != nil {
return err
} else if skip {
return nil
}
// Create a fresh template
if !exists {
return store.CreateTemplate(ctx, pl.s, res)
}
// Update existing template
switch n.cfg.OnExisting {
case resource.Skip:
return nil
case resource.MergeLeft:
res = mergeTemplates(n.t, res)
case resource.MergeRight:
res = mergeTemplates(res, n.t)
}
err = store.UpdateTemplate(ctx, pl.s, res)
if err != nil {
return err
}
n.res.Res = res
return nil
}