-
Notifications
You must be signed in to change notification settings - Fork 2
/
model.go
110 lines (87 loc) · 1.93 KB
/
model.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
105
106
107
108
109
110
package redis
import (
"reflect"
"time"
"unicode"
"libs.altipla.consulting/errors"
)
// Model should be implemented by any model that want to be serializable to redis keys.
type Model interface {
// IsRedisModel should always return true.
IsRedisModel() bool
}
// property represents a field of the model mapped to a database key.
type property struct {
// Name of the key.
Name string
// Struct field name.
Field string
// Value of the field.
Value interface{}
// Pointer to the value of the field.
ReflectValue reflect.Value
}
func extractModelProps(model Model) ([]*property, error) {
if !model.IsRedisModel() {
return nil, errors.Errorf("IsRedisModel should always return true for models")
}
v := reflect.ValueOf(model).Elem()
t := reflect.TypeOf(model).Elem()
props := []*property{}
for i := 0; i < t.NumField(); i++ {
fv := v.Field(i)
ft := t.Field(i)
if !startsWithUppercase(ft.Name) {
continue
}
prop := &property{
Name: ft.Name,
Field: ft.Name,
Value: fv.Interface(),
ReflectValue: fv,
}
tag := ft.Tag.Get("redis")
if tag != "" {
prop.Name = tag
}
if prop.Name == "-" {
continue
}
props = append(props, prop)
}
return props, nil
}
func isZero(value interface{}) bool {
switch v := value.(type) {
case string:
return len(v) == 0
case int32:
return v == 0
case int64:
return v == 0
case bool:
return !v
case time.Time:
return v.IsZero()
}
return false
}
func updatedProps(props []*property, model Model) []*property {
v := reflect.ValueOf(model).Elem()
var result []*property
for _, prop := range props {
result = append(result, &property{
Name: prop.Name,
Field: prop.Field,
Value: v.FieldByName(prop.Field).Interface(),
ReflectValue: v.FieldByName(prop.Field),
})
}
return result
}
func startsWithUppercase(s string) bool {
for _, r := range s {
return unicode.IsUpper(r)
}
return false
}