-
Notifications
You must be signed in to change notification settings - Fork 0
/
meta.go
352 lines (309 loc) · 10.6 KB
/
meta.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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
package resource
import (
"bytes"
"database/sql"
"encoding/json"
"fmt"
"reflect"
"strings"
"time"
"github.com/jinzhu/gorm"
"github.com/jinzhu/now"
"github.com/qor/qor"
"github.com/qor/qor/utils"
"github.com/qor/roles"
)
// Metaor interface
type Metaor interface {
GetName() string
GetFieldName() string
GetSetter() func(resource interface{}, metaValue *MetaValue, context *qor.Context)
GetFormattedValuer() func(interface{}, *qor.Context) interface{}
GetValuer() func(interface{}, *qor.Context) interface{}
GetResource() Resourcer
GetMetas() []Metaor
HasPermission(roles.PermissionMode, *qor.Context) bool
}
// ConfigureMetaBeforeInitializeInterface if a struct's field's type implemented this interface, it will be called when initializing a meta
type ConfigureMetaBeforeInitializeInterface interface {
ConfigureQorMetaBeforeInitialize(Metaor)
}
// ConfigureMetaInterface if a struct's field's type implemented this interface, it will be called after configed
type ConfigureMetaInterface interface {
ConfigureQorMeta(Metaor)
}
// Meta meta struct definition
type Meta struct {
Name string
FieldName string
Setter func(resource interface{}, metaValue *MetaValue, context *qor.Context)
Valuer func(interface{}, *qor.Context) interface{}
FormattedValuer func(interface{}, *qor.Context) interface{}
Permission *roles.Permission
Resource Resourcer
FieldStruct *gorm.StructField
}
// GetBaseResource get base resource from meta
func (meta Meta) GetBaseResource() Resourcer {
return meta.Resource
}
// GetName get meta's name
func (meta Meta) GetName() string {
return meta.Name
}
// GetFieldName get meta's field name
func (meta Meta) GetFieldName() string {
return meta.FieldName
}
// SetFieldName set meta's field name
func (meta *Meta) SetFieldName(name string) {
meta.FieldName = name
}
// GetSetter get setter from meta
func (meta Meta) GetSetter() func(resource interface{}, metaValue *MetaValue, context *qor.Context) {
return meta.Setter
}
// SetSetter set setter to meta
func (meta *Meta) SetSetter(fc func(resource interface{}, metaValue *MetaValue, context *qor.Context)) {
meta.Setter = fc
}
// GetValuer get valuer from meta
func (meta Meta) GetValuer() func(interface{}, *qor.Context) interface{} {
return meta.Valuer
}
// SetValuer set valuer for meta
func (meta *Meta) SetValuer(fc func(interface{}, *qor.Context) interface{}) {
meta.Valuer = fc
}
// GetFormattedValuer get formatted valuer from meta
func (meta *Meta) GetFormattedValuer() func(interface{}, *qor.Context) interface{} {
if meta.FormattedValuer != nil {
return meta.FormattedValuer
}
return meta.Valuer
}
// SetFormattedValuer set formatted valuer for meta
func (meta *Meta) SetFormattedValuer(fc func(interface{}, *qor.Context) interface{}) {
meta.FormattedValuer = fc
}
// HasPermission check has permission or not
func (meta Meta) HasPermission(mode roles.PermissionMode, context *qor.Context) bool {
if meta.Permission == nil {
return true
}
return meta.Permission.HasPermission(mode, context.Roles...)
}
// SetPermission set permission for meta
func (meta *Meta) SetPermission(permission *roles.Permission) {
meta.Permission = permission
}
// PreInitialize when will be run before initialize, used to fill some basic necessary information
func (meta *Meta) PreInitialize() error {
if meta.Name == "" {
utils.ExitWithMsg("Meta should have name: %v", reflect.TypeOf(meta))
} else if meta.FieldName == "" {
meta.FieldName = meta.Name
}
// parseNestedField used to handle case like Profile.Name
var parseNestedField = func(value reflect.Value, name string) (reflect.Value, string) {
fields := strings.Split(name, ".")
value = reflect.Indirect(value)
for _, field := range fields[:len(fields)-1] {
value = value.FieldByName(field)
}
return value, fields[len(fields)-1]
}
var getField = func(fields []*gorm.StructField, name string) *gorm.StructField {
for _, field := range fields {
if field.Name == name || field.DBName == name {
return field
}
}
return nil
}
var nestedField = strings.Contains(meta.FieldName, ".")
var scope = &gorm.Scope{Value: meta.Resource.GetResource().Value}
if nestedField {
subModel, name := parseNestedField(reflect.ValueOf(meta.Resource.GetResource().Value), meta.FieldName)
meta.FieldStruct = getField(scope.New(subModel.Interface()).GetStructFields(), name)
} else {
meta.FieldStruct = getField(scope.GetStructFields(), meta.FieldName)
}
return nil
}
// Initialize initialize meta, will set valuer, setter if haven't configure it
func (meta *Meta) Initialize() error {
var (
nestedField = strings.Contains(meta.FieldName, ".")
field = meta.FieldStruct
hasColumn = meta.FieldStruct != nil
)
var fieldType reflect.Type
if hasColumn {
fieldType = field.Struct.Type
for fieldType.Kind() == reflect.Ptr {
fieldType = fieldType.Elem()
}
}
// Set Meta Valuer
if meta.Valuer == nil {
if hasColumn {
meta.Valuer = func(value interface{}, context *qor.Context) interface{} {
scope := context.GetDB().NewScope(value)
fieldName := meta.FieldName
if nestedField {
fields := strings.Split(fieldName, ".")
fieldName = fields[len(fields)-1]
}
if f, ok := scope.FieldByName(fieldName); ok {
if f.Relationship != nil && f.Field.CanAddr() && !scope.PrimaryKeyZero() {
context.GetDB().Model(value).Related(f.Field.Addr().Interface(), meta.FieldName)
}
return f.Field.Interface()
}
return ""
}
} else {
utils.ExitWithMsg("Unsupported meta name %v for resource %v", meta.FieldName, reflect.TypeOf(meta.Resource.GetResource().Value))
}
}
if meta.Setter == nil && hasColumn {
if relationship := field.Relationship; relationship != nil {
if relationship.Kind == "belongs_to" || relationship.Kind == "many_to_many" {
meta.Setter = func(resource interface{}, metaValue *MetaValue, context *qor.Context) {
scope := &gorm.Scope{Value: resource}
reflectValue := reflect.Indirect(reflect.ValueOf(resource))
field := reflectValue.FieldByName(meta.FieldName)
if field.Kind() == reflect.Ptr {
if field.IsNil() {
field.Set(utils.NewValue(field.Type()).Elem())
}
for field.Kind() == reflect.Ptr {
field = field.Elem()
}
}
primaryKeys := utils.ToArray(metaValue.Value)
// associations not changed for belongs to
if relationship.Kind == "belongs_to" && len(relationship.ForeignFieldNames) == 1 {
oldPrimaryKeys := utils.ToArray(reflectValue.FieldByName(relationship.ForeignFieldNames[0]).Interface())
// if not changed
if fmt.Sprint(primaryKeys) == fmt.Sprint(oldPrimaryKeys) {
return
}
// if removed
if len(primaryKeys) == 0 {
field := reflectValue.FieldByName(relationship.ForeignFieldNames[0])
field.Set(reflect.Zero(field.Type()))
}
}
if len(primaryKeys) > 0 {
context.GetDB().Where(primaryKeys).Find(field.Addr().Interface())
}
// Replace many 2 many relations
if relationship.Kind == "many_to_many" {
if !scope.PrimaryKeyZero() {
context.GetDB().Model(resource).Association(meta.FieldName).Replace(field.Interface())
field.Set(reflect.Zero(field.Type()))
}
}
}
}
} else {
meta.Setter = func(resource interface{}, metaValue *MetaValue, context *qor.Context) {
if metaValue == nil {
return
}
value := metaValue.Value
fieldName := meta.FieldName
if nestedField {
fields := strings.Split(fieldName, ".")
fieldName = fields[len(fields)-1]
}
field := reflect.Indirect(reflect.ValueOf(resource)).FieldByName(fieldName)
if field.Kind() == reflect.Ptr {
if field.IsNil() {
field.Set(utils.NewValue(field.Type()).Elem())
}
for field.Kind() == reflect.Ptr {
field = field.Elem()
}
}
if field.IsValid() && field.CanAddr() {
switch field.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
field.SetInt(utils.ToInt(value))
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
field.SetUint(utils.ToUint(value))
case reflect.Float32, reflect.Float64:
field.SetFloat(utils.ToFloat(value))
case reflect.Bool:
// TODO: add test
if utils.ToString(value) == "true" {
field.SetBool(true)
} else {
field.SetBool(false)
}
default:
if scanner, ok := field.Addr().Interface().(sql.Scanner); ok {
if scanner.Scan(value) != nil {
scanner.Scan(utils.ToString(value))
}
} else if reflect.TypeOf("").ConvertibleTo(field.Type()) {
field.Set(reflect.ValueOf(utils.ToString(value)).Convert(field.Type()))
} else if reflect.TypeOf([]string{}).ConvertibleTo(field.Type()) {
field.Set(reflect.ValueOf(utils.ToArray(value)).Convert(field.Type()))
} else if rvalue := reflect.ValueOf(value); reflect.TypeOf(rvalue.Type()).ConvertibleTo(field.Type()) {
field.Set(rvalue.Convert(field.Type()))
} else if _, ok := field.Addr().Interface().(*time.Time); ok {
if str := utils.ToString(value); str != "" {
if newTime, err := now.Parse(str); err == nil {
field.Set(reflect.ValueOf(newTime))
}
}
} else {
var buf = bytes.NewBufferString("")
json.NewEncoder(buf).Encode(value)
if err := json.NewDecoder(strings.NewReader(buf.String())).Decode(field.Addr().Interface()); err != nil {
utils.ExitWithMsg("Can't set value %v to %v [meta %v]", reflect.TypeOf(value), field.Type(), meta)
}
}
}
}
}
}
}
if nestedField {
oldvalue := meta.Valuer
meta.Valuer = func(value interface{}, context *qor.Context) interface{} {
return oldvalue(getNestedModel(value, meta.FieldName, context), context)
}
oldSetter := meta.Setter
meta.Setter = func(resource interface{}, metaValue *MetaValue, context *qor.Context) {
oldSetter(getNestedModel(resource, meta.FieldName, context), metaValue, context)
}
}
return nil
}
func getNestedModel(value interface{}, fieldName string, context *qor.Context) interface{} {
model := reflect.Indirect(reflect.ValueOf(value))
fields := strings.Split(fieldName, ".")
for _, field := range fields[:len(fields)-1] {
if model.CanAddr() {
submodel := model.FieldByName(field)
if key := submodel.FieldByName("Id"); !key.IsValid() || key.Uint() == 0 {
if submodel.CanAddr() {
context.GetDB().Model(model.Addr().Interface()).Related(submodel.Addr().Interface())
model = submodel
} else {
break
}
} else {
model = submodel
}
}
}
if model.CanAddr() {
return model.Addr().Interface()
}
return nil
}