-
Notifications
You must be signed in to change notification settings - Fork 0
/
resource.go
96 lines (81 loc) · 2.55 KB
/
resource.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
package resource
import (
"reflect"
"github.com/jinzhu/gorm"
"github.com/qor/qor"
)
type Resource struct {
Name string
StructType string
primaryField *gorm.Field
Value interface{}
FindManyHandler func(interface{}, *qor.Context) error
FindOneHandler func(interface{}, *MetaValues, *qor.Context) error
Saver func(interface{}, *qor.Context) error
Deleter func(interface{}, *qor.Context) error
validators []func(interface{}, *MetaValues, *qor.Context) error
processors []func(interface{}, *MetaValues, *qor.Context) error
}
type Resourcer interface {
GetResource() *Resource
GetMetas([]string) []Metaor
CallFindMany(interface{}, *qor.Context) error
CallFindOne(interface{}, *MetaValues, *qor.Context) error
CallSaver(interface{}, *qor.Context) error
CallDeleter(interface{}, *qor.Context) error
NewSlice() interface{}
NewStruct() interface{}
}
func New(value interface{}, names ...string) *Resource {
structType := reflect.Indirect(reflect.ValueOf(value)).Type()
typeName := structType.String()
name := structType.Name()
for _, n := range names {
name = n
}
res := &Resource{Value: value, Name: name, StructType: typeName, Saver: DefaultSaver, FindOneHandler: DefaultFinder, FindManyHandler: DefaultSearcher, Deleter: DefaultDeleter}
return res
}
func (res *Resource) GetResource() *Resource {
return res
}
func (res *Resource) PrimaryField() *gorm.Field {
if res.primaryField == nil {
scope := gorm.Scope{Value: res.Value}
res.primaryField = scope.PrimaryField()
}
return res.primaryField
}
func (res *Resource) PrimaryDBName() (name string) {
field := res.PrimaryField()
if field != nil {
name = field.DBName
}
return
}
func (res *Resource) PrimaryFieldName() (name string) {
field := res.PrimaryField()
if field != nil {
name = field.Name
}
return
}
func (res *Resource) AddValidator(fc func(interface{}, *MetaValues, *qor.Context) error) {
res.validators = append(res.validators, fc)
}
func (res *Resource) AddProcessor(fc func(interface{}, *MetaValues, *qor.Context) error) {
res.processors = append(res.processors, fc)
}
func (res *Resource) NewSlice() interface{} {
sliceType := reflect.SliceOf(reflect.ValueOf(res.Value).Type())
slice := reflect.MakeSlice(sliceType, 0, 0)
slicePtr := reflect.New(sliceType)
slicePtr.Elem().Set(slice)
return slicePtr.Interface()
}
func (res *Resource) NewStruct() interface{} {
return reflect.New(reflect.Indirect(reflect.ValueOf(res.Value)).Type()).Interface()
}
func (res *Resource) GetMetas([]string) []Metaor {
panic("not defined")
}