-
Notifications
You must be signed in to change notification settings - Fork 0
/
base.go
100 lines (75 loc) · 1.75 KB
/
base.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
package db
import (
"reflect"
"strings"
)
type ID string
func IDp(s string) *ID {
id := ID(s)
return &id
}
type Base interface {
One(id ID, entity interface{}) error
List(list interface{}, options ...Options) error
Create(entity interface{}) error
Patch(table string, id ID, fields map[string]interface{}) error
Delete(table string, id ID) error
}
type TableNamer interface {
TableName() string
}
type Options struct {
View string // view for records filter
Filter interface{} // entity obj with not zero values filter fields
}
func TableName(entity interface{}) string {
t := reflect.ValueOf(entity).Type()
if t.Kind() == reflect.Ptr {
t = t.Elem()
}
if t.Kind() == reflect.Slice {
t = t.Elem()
}
if namer, ok := reflect.New(t).Interface().(TableNamer); ok {
return namer.TableName()
}
return t.Name() + "s"
}
func Fields(entity interface{}) map[string]interface{} {
v := reflect.ValueOf(entity)
if v.Kind() == reflect.Ptr {
v = v.Elem()
}
if v.Kind() != reflect.Struct {
panic("entity must be struct type or ptr")
}
m := map[string]interface{}{}
for i := 0; i < v.NumField(); i++ {
fType := v.Type().Field(i)
fName := fType.Name
fValue := v.Field(i)
if fName == "ID" {
continue
}
omitempty := strings.Contains(fType.Tag.Get("json"), "omitempty")
if omitempty && fValue.IsZero() {
continue
}
m[fName] = fValue.Interface()
if fType.Type.Kind() == reflect.Ptr {
fType.Type = fType.Type.Elem()
fValue = fValue.Elem()
}
if fType.Type == reflect.TypeOf(ID("")) {
m[fName] = []string{fValue.String()}
}
}
return m
}
func SetID(id ID, entity interface{}) {
v := reflect.ValueOf(entity)
if v.Kind() != reflect.Ptr {
return
}
v.Elem().FieldByName("ID").Set(reflect.ValueOf(id))
}