-
Notifications
You must be signed in to change notification settings - Fork 7
/
template.go
101 lines (90 loc) · 2.29 KB
/
template.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
package enthistory
import (
"fmt"
"strings"
"text/template"
"entgo.io/ent/schema/field"
"entgo.io/ent/entc/gen"
)
func extractUpdatedByKey(val any) string {
ub, ok := val.(*UpdatedBy)
if !ok || ub == nil {
return ""
}
return ub.key
}
func extractUpdatedByValueType(val any) string {
ub, ok := val.(*UpdatedBy)
if !ok || ub == nil {
return ""
}
switch ub.valueType {
case ValueTypeInt:
return "int"
case ValueTypeString:
return "string"
case ValueTypeUUID:
return "uuid.UUID"
default:
return ""
}
}
func isSlice(typeString string) bool {
return strings.HasPrefix(typeString, "[]")
}
func in(str string, list []string) bool {
for _, item := range list {
if item == str {
return true
}
}
return false
}
func isIdTypeUUID(node any) bool {
return node.(*gen.Type).IDType.Type == field.TypeUUID
}
func calculateHooks(original, history gen.Type) string {
var triggers []OpType
for n, f := range history.Annotations {
if n == "History" {
if h, ok := f.(map[string]any); ok {
for k, v := range h {
if k == "triggers" {
for _, op := range v.([]any) {
triggers = append(triggers, OpType(op.(string)))
}
}
}
}
}
}
if len(triggers) == 0 {
return "\n"
}
res := fmt.Sprintf("\n// %s hooks\n", original.Name)
const hookPrefix = "enthistory.HistoryTrigger"
const hookRegister = "c.%s.Use(%s)\n"
for _, trigger := range triggers {
switch {
case trigger == OpTypeInsert:
res += fmt.Sprintf(hookRegister, original.Name, fmt.Sprintf("%sInsert[*%sMutation]()", hookPrefix, original.Name))
case trigger == OpTypeUpdate:
res += fmt.Sprintf(hookRegister, original.Name, fmt.Sprintf("%sUpdate[*%sMutation]()", hookPrefix, original.Name))
case trigger == OpTypeDelete:
res += fmt.Sprintf(hookRegister, original.Name, fmt.Sprintf("%sDelete[*%sMutation]()", hookPrefix, original.Name))
}
}
return res
}
func parseTemplate(name, path string) *gen.Template {
t := gen.NewTemplate(name)
t.Funcs(template.FuncMap{
"extractUpdatedByKey": extractUpdatedByKey,
"extractUpdatedByValueType": extractUpdatedByValueType,
"isSlice": isSlice,
"in": in,
"isIdTypeUUID": isIdTypeUUID,
"calculateHooks": calculateHooks,
})
return gen.MustParse(t.ParseFS(_templates, path))
}