-
-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
entity_values.go
90 lines (69 loc) Β· 1.64 KB
/
entity_values.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
package entity
import (
"fmt"
"reflect"
)
// Map is an alias for map[string]interface{}.
type Map = map[string]interface{}
// ModelValues extracts Values from an entity model.
func ModelValues(m interface{}, omit ...string) (result Map, omitted []interface{}, err error) {
mustOmit := func(name string) bool {
for _, s := range omit {
if name == s {
return true
}
}
return false
}
r := reflect.ValueOf(m)
if r.Kind() != reflect.Pointer {
return result, omitted, fmt.Errorf("model interface expected")
}
values := r.Elem()
if kind := values.Kind(); kind != reflect.Struct {
return result, omitted, fmt.Errorf("model expected")
}
t := values.Type()
num := t.NumField()
omitted = make([]interface{}, 0, len(omit))
result = make(map[string]interface{}, num)
// Add exported fields to result.
for i := 0; i < num; i++ {
field := t.Field(i)
// Skip non-exported fields.
if !field.IsExported() {
continue
}
fieldName := field.Name
// Skip timestamps.
if fieldName == "" || fieldName == "UpdatedAt" || fieldName == "CreatedAt" {
continue
}
v := values.Field(i)
switch v.Kind() {
case reflect.Slice, reflect.Chan, reflect.Func, reflect.Map, reflect.UnsafePointer:
continue
case reflect.Struct:
if v.IsZero() {
continue
}
}
// Skip read-only fields.
if !v.CanSet() {
continue
}
// Skip omitted.
if mustOmit(fieldName) {
if !v.IsZero() {
omitted = append(omitted, v.Interface())
}
continue
}
// Add value to result.
result[fieldName] = v.Interface()
}
if len(result) == 0 {
return result, omitted, fmt.Errorf("no values")
}
return result, omitted, nil
}