-
Notifications
You must be signed in to change notification settings - Fork 0
/
bind.go
370 lines (298 loc) · 8.83 KB
/
bind.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
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
package grocery
import (
"errors"
"reflect"
"strconv"
"strings"
"time"
)
var mapType = reflect.TypeOf(&Map{})
var setType = reflect.TypeOf(&Set{})
// bind is used to load keys and values from data into ptr. Generally, data is
// the result of C.HGetAll(prefix + ":" + id), and ptr is a pointer to a
// struct that has been set up for usage with grocery.
func bind(prefix, id string, data map[string]string, ptr interface{}) error {
if ptr == nil {
return errors.New("ptr must not be nil")
} else if reflect.TypeOf(ptr).Kind() != reflect.Ptr || reflect.TypeOf(ptr).Elem().Kind() != reflect.Struct {
return errors.New("ptr must be a struct pointer")
} else if len(data) == 0 {
return errors.New("data must not be empty")
}
typ := reflect.TypeOf(ptr).Elem()
val := reflect.ValueOf(ptr).Elem()
return bindStruct(prefix, id, data, typ, val)
}
func bindStruct(prefix, id string, data map[string]string, typ reflect.Type, val reflect.Value) error {
for i := 0; i < typ.NumField(); i++ {
typeField := typ.Field(i)
structField := val.Field(i)
// Skip unexported fields
if !structField.CanSet() {
continue
}
inputFieldName := typeField.Tag.Get("grocery")
if inputFieldName == "-" {
// Skip values that shouldn't be stored
continue
} else if structField.Kind() == reflect.Struct && typeField.Anonymous {
// Recurse on embedded structs
bindStruct(prefix, id, data, typeField.Type, structField)
continue
} else if strings.Contains(inputFieldName, ",") {
inputFieldName = strings.Split(inputFieldName, ",")[0]
} else if inputFieldName == "" {
// Tag was not specified, assume field name
if len(typeField.Name) > 1 {
inputFieldName = strings.ToLower(string(typeField.Name[0])) + string(typeField.Name[1:])
} else {
inputFieldName = strings.ToLower(typeField.Name)
}
}
switch typeField.Type.Kind() {
case reflect.Ptr:
// New item to set in struct
res := reflect.New(typeField.Type.Elem())
if typeField.Type == mapType || (typeField.Type.Elem().Kind() == reflect.Struct && res.Elem().FieldByName("CustomMapType").IsValid()) {
// This is a map
m, err := C.HGetAll(ctx, prefix+":"+id+":"+inputFieldName).Result()
if err != nil {
return err
}
for k := range m {
res.MethodByName("Store").Call([]reflect.Value{
reflect.ValueOf(k),
reflect.ValueOf(m[k]),
})
}
if setupMethod := res.MethodByName("Setup"); setupMethod.IsValid() {
setupMethod.Call([]reflect.Value{})
}
structField.Set(res)
} else if typeField.Type == setType || (typeField.Type.Elem().Kind() == reflect.Struct && res.Elem().FieldByName("CustomSetType").IsValid()) {
// This is a set
s, err := C.SMembers(ctx, prefix+":"+id+":"+inputFieldName).Result()
if err != nil {
return err
}
for _, val := range s {
res.MethodByName("Add").Call([]reflect.Value{
reflect.ValueOf(val),
})
}
if setupMethod := res.MethodByName("Setup"); setupMethod.IsValid() {
setupMethod.Call([]reflect.Value{})
}
structField.Set(res)
} else if typeField.Type.Elem().Kind() == reflect.Struct {
if _, ok := typeField.Type.Elem().FieldByName("Base"); ok {
// This is a reference to a model that we should load from Redis
id := data[inputFieldName]
// Load data from redis
subPrefix := strings.ToLower(res.Type().Elem().Name())
dat, err := C.HGetAll(ctx, subPrefix+":"+id).Result()
if err != nil {
return err
} else if len(dat) == 0 {
continue
}
err = bindStruct(subPrefix, id, dat, res.Type().Elem(), res.Elem())
if err != nil {
return err
}
// Set ID
val := res.Elem()
fi := reflect.Indirect(val).FieldByName("ID")
if fi.String() != id {
fi.SetString(id)
}
structField.Set(res)
// Call post-load hook
postLoad := res.MethodByName("PostLoad")
if postLoad.IsValid() {
postLoad.Call([]reflect.Value{})
}
} else {
return errors.New("Can't set unsupported struct with key " + inputFieldName)
}
} else {
inputValue, exists := data[inputFieldName]
if !exists {
continue
}
if err := setFieldWithKind(typeField.Type.Kind(), inputValue, structField); err != nil {
return err
}
}
case reflect.Slice:
ids, err := C.LRange(ctx, prefix+":"+id+":"+inputFieldName, 0, -1).Result()
if err != nil {
return err
}
arr := reflect.MakeSlice(typeField.Type, 0, len(ids))
for _, itemID := range ids {
if typeField.Type.Elem().Kind() == reflect.String {
// This is just a string slice
arr = reflect.Append(arr, reflect.ValueOf(itemID))
} else if _, ok := typeField.Type.Elem().Elem().FieldByName("Base"); ok {
// This is a reference to a model that we should load from Redis
ptr := reflect.New(typeField.Type.Elem().Elem())
// Load data from redis
subPrefix := strings.ToLower(ptr.Type().Elem().Name())
dat, err := C.HGetAll(ctx, subPrefix+":"+itemID).Result()
if err != nil {
return err
}
err = bindStruct(subPrefix, itemID, dat, ptr.Type().Elem(), ptr.Elem())
if err != nil {
return err
}
// Set ID
val := ptr.Elem()
fi := reflect.Indirect(val).FieldByName("ID")
if fi.String() != itemID {
fi.SetString(itemID)
}
arr = reflect.Append(arr, ptr)
} else {
return errors.New("can't set unsupported struct")
}
}
structField.Set(arr)
case reflect.Bool:
if loadFunc := structField.MethodByName("Load"); loadFunc.IsValid() {
// Load custom boolean values
ret := loadFunc.Call([]reflect.Value{
reflect.ValueOf(id),
reflect.ValueOf(inputFieldName),
})
val := strconv.FormatBool(ret[0].Bool())
if !ret[1].IsNil() {
return ret[1].Interface().(error)
}
if err := setFieldWithKind(structField.Kind(), val, structField); err != nil {
return err
}
} else {
inputValue, exists := data[inputFieldName]
if !exists {
continue
}
if err := setFieldWithKind(typeField.Type.Kind(), inputValue, structField); err != nil {
return err
}
}
default:
inputValue, exists := data[inputFieldName]
if !exists {
continue
}
if err := setFieldWithKind(typeField.Type.Kind(), inputValue, structField); err != nil {
return err
}
}
}
return nil
}
func setFieldWithKind(valueKind reflect.Kind, val string, structField reflect.Value) error {
switch valueKind {
case reflect.Ptr:
return setFieldWithKind(structField.Elem().Kind(), val, structField.Elem())
case reflect.Int:
return setIntField(val, 0, structField)
case reflect.Int8:
return setIntField(val, 8, structField)
case reflect.Int16:
return setIntField(val, 16, structField)
case reflect.Int32:
return setIntField(val, 32, structField)
case reflect.Int64:
return setIntField(val, 64, structField)
case reflect.Uint:
return setUintField(val, 0, structField)
case reflect.Uint8:
return setUintField(val, 8, structField)
case reflect.Uint16:
return setUintField(val, 16, structField)
case reflect.Uint32:
return setUintField(val, 32, structField)
case reflect.Uint64:
return setUintField(val, 64, structField)
case reflect.Bool:
return setBoolField(val, structField)
case reflect.Float32:
return setFloatField(val, 32, structField)
case reflect.Float64:
return setFloatField(val, 64, structField)
case reflect.String:
structField.SetString(val)
case reflect.Struct:
switch structField.Type() {
case reflect.TypeOf(time.Now()):
timeInt, _ := strconv.ParseInt(val, 10, 64)
existingTimeInt := structField.MethodByName("Unix").Call([]reflect.Value{})[0].Int()
if existingTimeInt == timeInt {
return nil
}
timeVal := time.Unix(int64(timeInt), 0)
structField.Set(reflect.ValueOf(timeVal))
default:
return errors.New("unknown type")
}
default:
return errors.New("unknown type")
}
return nil
}
func setIntField(value string, bitSize int, field reflect.Value) error {
if value == "" {
value = "0"
}
val, err := strconv.ParseInt(value, 10, bitSize)
if err != nil {
return err
}
if val != field.Int() {
field.SetInt(val)
}
return nil
}
func setUintField(value string, bitSize int, field reflect.Value) error {
if value == "" {
value = "0"
}
val, err := strconv.ParseUint(value, 10, bitSize)
if err != nil {
return err
}
if val != field.Uint() {
field.SetUint(val)
}
return nil
}
func setBoolField(value string, field reflect.Value) error {
if value == "" {
value = "false"
}
val, err := strconv.ParseBool(value)
if err != nil {
return err
}
if val != field.Bool() {
field.SetBool(val)
}
return nil
}
func setFloatField(value string, bitSize int, field reflect.Value) error {
if value == "" {
value = "0.0"
}
val, err := strconv.ParseFloat(value, bitSize)
if err != nil {
return err
}
if val != field.Float() {
field.SetFloat(val)
}
return nil
}