/
store.go
848 lines (684 loc) · 18.3 KB
/
store.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
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
//Package store provides a registry and interface to interact with a store repository against model entities.
package store
import (
"encoding/json"
"errors"
"fmt"
"log"
"reflect"
"strings"
"github.com/DanielRenne/GoCore/core/extensions"
)
const (
WebSocketStoreKey = "WebSocket"
PathAdd = "Add"
PathRemove = "Remove"
)
type pathValue struct {
Path string `json:"Path"`
Value interface{} `json:"Value"`
}
//OnRecordUpdate allows an application to publish all changes of a record
var OnRecordUpdate []string
var OnChangeRecord func(key string, id string, x interface{})
//OnChange provides inserts, updates, and deletes to the store key.
var OnChange func(key string, id string, path string, x interface{}, err error)
//Get gets a collection entity by id.
func Get(key string, id string, joins []string) (x interface{}, err error) {
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("%+v", r)
return
}
}()
collection, ok := getRegistry(key)
if !ok {
return
}
obj, err := collection.ById(id, joins)
if err != nil {
return
}
x = obj.Elem().Interface()
return
}
//GetByFilter gets a collection entity by filter.
func GetCountByFilter(key string, filter map[string]interface{}, inFilter map[string]interface{}, excludeFilter map[string]interface{}, joins []string) (x interface{}, err error) {
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("%+v", r)
return
}
}()
collection, ok := getRegistry(key)
if !ok {
return
}
count, err := collection.CountByFilter(filter, inFilter, excludeFilter, joins)
if err != nil {
return
}
x = count
return
}
//GetByFilter gets a collection entity by filter.
func GetByFilter(key string, filter map[string]interface{}, inFilter map[string]interface{}, excludeFilter map[string]interface{}, joins []string) (x interface{}, err error) {
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("%+v", r)
return
}
}()
collection, ok := getRegistry(key)
if !ok {
return
}
obj, err := collection.ByFilter(filter, inFilter, excludeFilter, joins)
if err != nil {
return
}
x = obj.Elem().Interface()
return
}
//GetByPath gets a collection entity-property value by id & path.
func GetByPath(key string, id string, joins []string, path string) (x interface{}, err error) {
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("%+v", r)
return
}
}()
collection, ok := getRegistry(key)
if !ok {
return
}
obj, err := collection.ById(id, joins)
if err != nil {
return
}
objElem := obj.Elem()
if path == "*" {
x = obj.Interface()
return
}
fields := strings.Split(path, ".")
depth := len(fields)
properties := []reflect.Value{}
for i := range fields {
fieldName := fields[i]
arrayIndex := -1
if strings.Contains(fieldName, "[") {
arraySplit := strings.Split(fieldName, "[")
fieldName = arraySplit[0]
arrayIndex = extensions.StringToInt(strings.Replace(arraySplit[1], "]", "", -1))
}
var fieldValue reflect.Value
if i == 0 {
fieldValue = objElem.FieldByName(fieldName)
} else {
if properties[i-1].IsValid() {
fieldValue = properties[i-1].FieldByName(fieldName)
} else {
fieldValue = reflect.Value{}
}
}
if arrayIndex == -1 {
properties = append(properties, fieldValue)
} else {
if fieldValue.Len() >= arrayIndex+1 {
properties = append(properties, fieldValue.Index(arrayIndex))
} else {
properties = append(properties, reflect.Value{})
}
}
if i+1 == depth {
if properties[i].IsValid() && properties[i].CanInterface() {
x = properties[i].Interface()
} else {
x = nil
}
}
}
return
}
//GetByPathBatch gets a collection entity-property values by id & path.
func GetByPathBatch(key string, id string, joins []string, paths []string) (x interface{}, err error) {
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("%+v", r)
return
}
}()
collection, ok := getRegistry(key)
if !ok {
return
}
obj, err := collection.ById(id, joins)
if err != nil {
return
}
objElem := obj.Elem()
results := []pathValue{}
for j := range paths {
path := paths[j]
if path == "*" {
var pv pathValue
pv.Path = path
pv.Value = obj.Interface()
results = append(results, pv)
continue
}
fields := strings.Split(path, ".")
depth := len(fields)
properties := []reflect.Value{}
for i := range fields {
fieldName := fields[i]
arrayIndex := -1
if strings.Contains(fieldName, "[") {
arraySplit := strings.Split(fieldName, "[")
fieldName = arraySplit[0]
arrayIndex = extensions.StringToInt(strings.Replace(arraySplit[1], "]", "", -1))
}
var fieldValue reflect.Value
if i == 0 {
fieldValue = objElem.FieldByName(fieldName)
} else {
if properties[i-1].IsValid() {
fieldValue = properties[i-1].FieldByName(fieldName)
} else {
fieldValue = reflect.Value{}
}
}
if arrayIndex == -1 {
properties = append(properties, fieldValue)
} else {
if fieldValue.Len() >= arrayIndex+1 {
properties = append(properties, fieldValue.Index(arrayIndex))
} else {
properties = append(properties, reflect.Value{})
}
}
if i+1 == depth {
var pv pathValue
pv.Path = path
if properties[i].IsValid() && properties[i].CanInterface() {
pv.Value = properties[i].Interface()
} else {
pv.Value = nil
}
results = append(results, pv)
}
}
}
x = results
return
}
//Publish fetches the record / path and publishes out to all subscribers.
func Publish(key string, id string, path string, logger func(string, string)) {
defer func() {
if r := recover(); r != nil {
logger("Recover", fmt.Sprintf("%+v", r))
if OnChange != nil {
logger("1 Store Publish Error:"+fmt.Errorf("%+v", r).Error(), "")
OnChange(key, id, path, nil, fmt.Errorf("%+v", r))
}
}
}()
collection, ok := getRegistry(key)
if !ok {
return
}
obj, err := collection.ById(id, []string{})
if err != nil {
log.Printf("%s%s", "Error Getting Collection Object by id. ", err.Error())
return
}
if path == "" {
if OnChange != nil {
OnChange(key, id, "", obj.Interface(), nil)
}
} else {
var x interface{}
objElem := obj.Elem()
fields := strings.Split(path, ".")
depth := len(fields)
properties := []reflect.Value{}
for i := range fields {
fieldName := fields[i]
arrayIndex := -1
if strings.Contains(fieldName, "[") {
arraySplit := strings.Split(fieldName, "[")
fieldName = arraySplit[0]
arrayIndex = extensions.StringToInt(strings.Replace(arraySplit[1], "]", "", -1))
}
var fieldValue reflect.Value
if i == 0 {
fieldValue = objElem.FieldByName(fieldName)
} else {
fieldValue = properties[i-1].FieldByName(fieldName)
}
if arrayIndex == -1 {
properties = append(properties, fieldValue)
} else {
properties = append(properties, fieldValue.Index(arrayIndex))
}
if i+1 == depth {
x = properties[i].Interface()
}
}
if OnChange != nil {
OnChange(key, id, path, x, nil)
}
}
}
//Set updates a collection by id, path.
func Set(key string, id string, path string, x interface{}, logger func(string, string)) (err error) {
defer func() {
if r := recover(); r != nil {
logger("Recover", fmt.Sprintf("%+v", r))
if OnChange != nil {
logger("2 Store Set Error:"+fmt.Errorf("%+v", r).Error(), "")
OnChange(key, id, path, x, fmt.Errorf("%+v", r))
}
}
}()
collection, ok := getRegistry(key)
if !ok {
err = errors.New("Invalid registry key")
return
}
obj, err := collection.ById(id, []string{})
if err != nil {
log.Printf("%s%s", "Error Getting Collection Object by id. ", err.Error())
return
}
objElem := obj.Elem()
if path == "" {
method := obj.MethodByName("ParseInterface")
in := []reflect.Value{}
in = append(in, reflect.ValueOf(x))
values := method.Call(in)
if values[0].Interface() != nil {
var ok bool
err, ok = values[0].Interface().(error)
if ok {
logger("Error", err.Error())
log.Printf("%s%+v\n", "Error Parsing Object.", err.Error())
if OnChange != nil {
logger("3 Store Set Error:"+err.Error(), "")
OnChange(key, id, path, x, err)
}
return
}
}
} else {
fields := strings.Split(path, ".")
depth := len(fields)
properties := []reflect.Value{}
for i := range fields {
fieldName := fields[i]
arrayIndex := -1
if strings.Contains(fieldName, "[") {
arraySplit := strings.Split(fieldName, "[")
fieldName = arraySplit[0]
arrayIndex = extensions.StringToInt(strings.Replace(arraySplit[1], "]", "", -1))
}
var fieldValue reflect.Value
if i == 0 {
fieldValue = objElem.FieldByName(fieldName)
} else {
fieldValue = properties[i-1].FieldByName(fieldName)
}
if arrayIndex == -1 {
properties = append(properties, fieldValue)
} else {
properties = append(properties, fieldValue.Index(arrayIndex))
}
if i+1 == depth {
if properties[i].CanSet() {
propInterface := properties[i].Interface()
if propInterface != nil {
propType := reflect.TypeOf(propInterface).String()
// logger("PropType", fmt.Sprintf("%+v", propType))
if propType == "int" {
floatVal, ok := x.(float64)
if ok {
x = int(floatVal)
}
intVal, ok := x.(string)
if ok {
x = extensions.StringToInt(intVal)
}
} else if propType == "float64" {
intVal, ok := x.(int)
if ok {
x = float64(intVal)
}
floatVal, ok := x.(string)
if ok {
x = extensions.StringToFloat(floatVal, 0)
}
} else if propType == "[]int" {
x = interfaceToIntArray(x)
}
}
if arrayIndex == -1 {
valueToSet, err2 := collection.ReflectByFieldName(fieldName, x)
if err2 != nil {
logger("Error Setting Value to Store", fmt.Sprintf("%+v", valueToSet)+"\nError: "+err2.Error())
logger("4 Store Set Error: "+err2.Error(), "")
OnChange(key, id, path, x, err2)
return
}
properties[i].Set(valueToSet)
} else {
properties[i].Set(reflect.ValueOf(x))
}
}
}
}
}
method := obj.MethodByName("Save")
in := []reflect.Value{}
values := method.Call(in)
if values[0].Interface() != nil {
var ok bool
err, ok = values[0].Interface().(error)
if ok {
logger("Error", err.Error())
log.Printf("%s%+v\n", "Error Saving Object.", err.Error())
if OnChange != nil {
logger("5 Store Publish Error:"+err.Error(), "")
OnChange(key, id, path, x, err)
}
return
}
}
if OnChange != nil {
OnChange(key, id, path, x, nil)
}
return
// log.Printf("%s%+v\n", "UPdated Entity ", objElem)
}
//Append adds to an array field.
func Append(key string, id string, path string, x interface{}, logger func(string, string)) (y interface{}, err error) {
defer func() {
if r := recover(); r != nil {
logger("Recover", fmt.Sprintf("%+v", r))
if OnChange != nil {
logger("6 Store Append Error:"+err.Error(), "")
OnChange(key, id, path, x, fmt.Errorf("%+v", r))
}
}
}()
collection, ok := getRegistry(key)
if !ok {
return
}
obj, err := collection.ById(id, []string{})
if err != nil {
log.Printf("%s%s", "Error Getting Collection Object by id. ", err.Error())
return
}
objElem := obj.Elem()
fields := strings.Split(path, ".")
depth := len(fields)
properties := []reflect.Value{}
var updatedArray reflect.Value
for i := range fields {
fieldName := fields[i]
arrayIndex := -1
if strings.Contains(fieldName, "[") {
arraySplit := strings.Split(fieldName, "[")
fieldName = arraySplit[0]
arrayIndex = extensions.StringToInt(strings.Replace(arraySplit[1], "]", "", -1))
}
var fieldValue reflect.Value
if i == 0 {
fieldValue = objElem.FieldByName(fieldName)
} else {
fieldValue = properties[i-1].FieldByName(fieldName)
}
if arrayIndex == -1 {
properties = append(properties, fieldValue)
} else {
properties = append(properties, fieldValue.Index(arrayIndex))
}
if i+1 == depth {
if properties[i].CanSet() {
propType := reflect.TypeOf(properties[i].Interface()).String()
if propType == "int" {
floatVal, ok := x.(float64)
if ok {
x = int(floatVal)
}
} else if propType == "float64" {
intVal, ok := x.(int)
if ok {
x = float64(intVal)
}
}
valueToSet, err := collection.ReflectBaseTypeByFieldName(fieldName, x)
if err != nil {
logger("Error Setting Value to Store", fmt.Sprintf("%+v", valueToSet)+"\nError: "+err.Error())
logger("7 Store Append Error:"+err.Error(), "")
OnChange(key, id, path, x, err)
}
properties[i].Set(reflect.Append(properties[i], valueToSet))
updatedArray = properties[i]
}
}
}
method := obj.MethodByName("Save")
in := []reflect.Value{}
values := method.Call(in)
if values[0].Interface() != nil {
errInterface, ok := values[0].Interface().(error)
if ok {
logger("Error", errInterface.Error())
log.Printf("%s%+v\n", "Error Saving Object.", errInterface.Error())
if OnChange != nil {
logger("8 Store Append Error:"+err.Error(), "")
OnChange(key, id, path, x, errInterface)
}
err = errInterface
return
}
}
if OnChange != nil {
OnChange(key, id, path, updatedArray.Interface(), nil)
}
y = updatedArray.Interface()
return
}
//Splice removes to an array field.
func Splice(key string, id string, path string, x interface{}, logger func(string, string)) (y interface{}, err error) {
defer func() {
if r := recover(); r != nil {
logger("Recover", fmt.Sprintf("%+v", r))
if OnChange != nil {
logger("9 Store Splice Error:"+err.Error(), "")
OnChange(key, id, path, x, fmt.Errorf("%+v", r))
}
}
}()
collection, ok := getRegistry(key)
if !ok {
return
}
obj, err := collection.ById(id, []string{})
if err != nil {
log.Printf("%s%s", "Error Getting Collection Object by id. ", err.Error())
return
}
objElem := obj.Elem()
fields := strings.Split(path, ".")
depth := len(fields)
properties := []reflect.Value{}
var updatedArray reflect.Value
for i := range fields {
fieldName := fields[i]
arrayIndex := -1
if strings.Contains(fieldName, "[") {
arraySplit := strings.Split(fieldName, "[")
fieldName = arraySplit[0]
arrayIndex = extensions.StringToInt(strings.Replace(arraySplit[1], "]", "", -1))
}
var fieldValue reflect.Value
if i == 0 {
fieldValue = objElem.FieldByName(fieldName)
} else {
fieldValue = properties[i-1].FieldByName(fieldName)
}
if arrayIndex == -1 {
properties = append(properties, fieldValue)
} else {
properties = append(properties, fieldValue.Index(arrayIndex))
}
if i+1 == depth {
if properties[i].CanSet() {
propType := reflect.TypeOf(x).String()
if propType == "float64" {
floatVal, ok := x.(float64)
if ok {
x = int(floatVal)
}
}
index := x.(int)
length := properties[i].Len()
properties[i].Set(reflect.AppendSlice(properties[i].Slice(0, index), properties[i].Slice(index+1, length)))
updatedArray = properties[i]
}
}
}
method := obj.MethodByName("Save")
in := []reflect.Value{}
values := method.Call(in)
if values[0].Interface() != nil {
errInterface, ok := values[0].Interface().(error)
if ok {
logger("Error", errInterface.Error())
log.Printf("%s%+v\n", "Error Saving Object.", errInterface.Error())
if OnChange != nil {
logger("10 Store Append Error:"+errInterface.Error(), "")
OnChange(key, id, path, x, errInterface)
}
err = errInterface
return
}
}
if OnChange != nil {
OnChange(key, id, path, updatedArray.Interface(), nil)
}
y = updatedArray.Interface()
return
}
//Add adds an entity to the collection and returns it.
func Add(key string, x interface{}, logger func(string, string)) (y interface{}, err error) {
defer func() {
if r := recover(); r != nil {
logger("Recover", fmt.Sprintf("%+v", r))
if OnChange != nil {
logger("11 Store Add Error:"+fmt.Errorf("%+v", r).Error(), "")
OnChange(key, "", "", x, fmt.Errorf("%+v", r))
}
}
}()
collection, ok := getRegistry(key)
if !ok {
return
}
obj := collection.NewByReflection()
if x != nil {
data, errMarshal := json.Marshal(x)
if errMarshal != nil {
if OnChange != nil {
logger("12 Store Add Error:"+errMarshal.Error(), "")
OnChange(key, "", "", x, errMarshal)
}
return
}
errUnMarshal := json.Unmarshal(data, obj.Interface())
if errUnMarshal != nil {
if OnChange != nil {
logger("13 Store Add Error:"+errUnMarshal.Error(), "")
OnChange(key, "", "", x, errUnMarshal)
}
return
}
}
method := obj.MethodByName("Save")
in := []reflect.Value{}
values := method.Call(in)
if values[0].Interface() != nil {
errSave, ok := values[0].Interface().(error)
if ok {
logger("Error", err.Error())
log.Printf("%s%+v\n", "Error Saving Object.", err.Error())
if OnChange != nil {
logger("14 Store Add Error:"+err.Error(), "")
OnChange(key, "", "", x, err)
}
err = errSave
return
}
}
methodGetID := obj.MethodByName("GetId")
inID := []reflect.Value{}
idValues := methodGetID.Call(inID)
if OnChange != nil {
OnChange(key, idValues[0].Interface().(string), "", obj.Interface(), nil)
}
y = obj.Interface()
return
}
//Remove removes an entity from the collection and returns the Id Removed.
func Remove(key string, id string) (err error) {
defer func() {
if r := recover(); r != nil {
if OnChange != nil {
OnChange(key, "", "", nil, fmt.Errorf("%+v", r))
}
}
}()
collection, ok := getRegistry(key)
if !ok {
return
}
obj, err := collection.ById(id, []string{})
if err != nil {
return
}
methodGetID := obj.MethodByName("GetId")
inID := []reflect.Value{}
idValues := methodGetID.Call(inID)
method := obj.MethodByName("Delete")
in := []reflect.Value{}
values := method.Call(in)
if values[0].Interface() != nil {
errSave, ok := values[0].Interface().(error)
if ok {
log.Printf("%s%+v\n", "Error Deleting Object.", err.Error())
if OnChange != nil {
OnChange(key, "", "", nil, err)
}
err = errSave
return
}
}
if OnChange != nil {
OnChange(key, idValues[0].Interface().(string), "", nil, nil)
}
return
}
func interfaceToIntArray(slice interface{}) (items []int) {
s := reflect.ValueOf(slice)
if s.Kind() != reflect.Slice {
return
}
ret := make([]int, s.Len())
for i := 0; i < s.Len(); i++ {
ret[i] = int(s.Index(i).Interface().(float64))
}
return ret
}