forked from uadmin/uadmin
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathd_api_helper.go
848 lines (749 loc) · 25.3 KB
/
d_api_helper.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 uadmin
import (
"net/http"
"net/url"
"reflect"
"strings"
"time"
)
func getURLArgs(r *http.Request) map[string]string {
params := map[string]string{}
// First Parse GET params
getParams := strings.Split(r.URL.RawQuery, "&")
for _, param := range getParams {
paramParts := strings.SplitN(param, "=", 2)
if len(paramParts) != 2 {
continue
}
// Skip session
if paramParts[0] == "session" {
continue
}
// Skip csrf
if paramParts[0] == "x-csrf-token" {
continue
}
// unescape URL except for $or because it uses + for nested AND
val := paramParts[1]
if paramParts[0] != "$or" {
val, _ = url.QueryUnescape(paramParts[1])
}
if _, ok := params[paramParts[0]]; ok {
params[paramParts[0]] += "," + val
} else {
params[paramParts[0]] = val
}
}
// Parse post parameters
for k, v := range r.PostForm {
if len(v) < 1 {
continue
}
// Skip session
if k == "session" {
continue
}
// Skip csrf
if k == "x-csrf-token" {
continue
}
if _, ok := params[k]; ok {
params[k] += "," + strings.Join(v, ",")
} else {
params[k] = strings.Join(v, ",")
}
}
return params
}
func getFilters(r *http.Request, params map[string]string, tableName string, schema *ModelSchema) (query string, args []interface{}) {
qParts := []string{}
args = []interface{}{}
for k, v := range params {
// TODO: Explain the condition with a URL to specs
// Anything that starts with a '$' or '_' in assigning a field name
// will be skipped. '$' is used as a special parameter such as limit,
// offset, and order while '_' is used for writing data (Add/Edit).
// This loop executes either by assigning an exact field name
// or by using $or parameter as a special case. It compares which of
// the assigned parameters matches a specified criteria.
// http://example.com/api/d/modelname/read/?f=1
// http://example.com/api/d/modelname/read/?$or=f=1|f=2
if (k[0] == '$' && k != "$or" && k != "$q") || k[0] == '_' {
continue
}
if k == "$or" {
orQList := strings.Split(v, "|")
orQParts := []string{}
orArgs := []interface{}{}
for _, orQ := range orQList {
andQParts := []string{}
andArgs := []interface{}{}
andQList := strings.Split(orQ, "+")
for _, andQ := range andQList {
andParts := strings.SplitN(andQ, "=", 2)
if len(andParts) != 2 {
continue
}
andQParts = append(andQParts, getQueryOperator(r, andParts[0], tableName))
andArgs = append(andArgs, getQueryArg(andParts[0], andParts[1])...)
}
orQParts = append(orQParts, "("+strings.Join(andQParts, " AND ")+")")
orArgs = append(orArgs, andArgs...)
}
qParts = append(qParts, "("+strings.Join(orQParts, " OR ")+")")
args = append(args, orArgs...)
} else if k == "$q" {
orQParts := []string{}
orArgs := []interface{}{}
for _, field := range schema.Fields {
if field.Searchable {
// TODO: Support non-string types
if field.TypeName == "string" {
orQParts = append(orQParts, getQueryOperator(r, field.ColumnName+"__icontains", tableName))
orArgs = append(orArgs, getQueryArg(field.ColumnName+"__icontains", v)...)
} else if field.Type == "number" {
orQParts = append(orQParts, getQueryOperator(r, field.ColumnName+"__contains", tableName))
orArgs = append(orArgs, getQueryArg(field.ColumnName+"__contains", v)...)
}
}
}
if len(orQParts) != 0 {
qParts = append(qParts, "("+strings.Join(orQParts, " OR ")+")")
args = append(args, orArgs...)
}
} else if isM2MField(k, schema) {
// M2M filter
qParts = append(qParts, getM2MQueryOperator(k, schema))
args = append(args, getM2MQueryArg(k, v, schema)...)
} else {
qParts = append(qParts, getQueryOperator(r, k, tableName))
args = append(args, getQueryArg(k, v)...)
}
}
query = strings.Join(qParts, " AND ")
if !strings.Contains(query, "deleted_at") {
if val, ok := params["$deleted"]; ok {
if val == "0" || val == "false" {
qParts = append(qParts, tableName+".deleted_at IS NULL")
}
} else {
qParts = append(qParts, tableName+".deleted_at IS NULL")
}
query = strings.Join(qParts, " AND ")
}
return query, args
}
func isM2MField(v string, schema *ModelSchema) bool {
f := schema.FieldByColumnName(v)
if f == nil {
return false
}
return f.Type == cM2M
}
func getM2MQueryOperator(v string, schema *ModelSchema) string {
return "id IN (?)"
}
func getM2MQueryArg(k, v string, schema *ModelSchema) []interface{} {
f := schema.FieldByColumnName(k)
t1 := schema.ModelName
t2 := strings.ToLower(f.TypeName)
SQL := sqlDialect[Database.Type]["selectM2MT2"]
SQL = strings.ReplaceAll(SQL, "{TABLE1}", t1)
SQL = strings.ReplaceAll(SQL, "{TABLE2}", t2)
type M2MTable struct {
Table1ID uint `gorm:"column:table1_id"`
Table2ID uint `gorm:"column:table2_id"`
}
values := []M2MTable{}
err := GetDB().Raw(SQL, strings.Split(v, ",")).Scan(&values).Error
if err != nil {
Trail(ERROR, "Unable to get M2M args. %s", err)
return []interface{}{}
}
returnArgs := make([]interface{}, len(values))
for i := range values {
returnArgs[i] = values[i].Table1ID
}
return []interface{}{returnArgs}
}
func getQueryOperator(r *http.Request, v string, tableName string) string {
// Determine if the query is negated
n := len(v) > 0 && v[0] == '!'
nTerm := ""
if n {
nTerm = " NOT"
v = v[1:]
}
// add table name
if SQLInjection(r, v, "") {
return ""
}
if !strings.Contains(v, ".") {
v = columnEnclosure() + tableName + columnEnclosure() + "." + columnEnclosure() + v
} else {
vParts := strings.SplitN(v, ".", 2)
v = columnEnclosure() + vParts[0] + columnEnclosure() + "." + columnEnclosure() + vParts[1]
}
if strings.HasSuffix(v, "__gt") {
if n {
return strings.TrimSuffix(v, "__gt") + columnEnclosure() + " <= ?"
}
return strings.TrimSuffix(v, "__gt") + columnEnclosure() + " > ?"
}
if strings.HasSuffix(v, "__gte") {
if n {
return strings.TrimSuffix(v, "__gte") + columnEnclosure() + " < ?"
}
return strings.TrimSuffix(v, "__gte") + columnEnclosure() + " >= ?"
}
if strings.HasSuffix(v, "__lt") {
if n {
return strings.TrimSuffix(v, "__lt") + columnEnclosure() + " >= ?"
}
return strings.TrimSuffix(v, "__lt") + columnEnclosure() + " < ?"
}
if strings.HasSuffix(v, "__lte") {
if n {
return strings.TrimSuffix(v, "__lte") + columnEnclosure() + " > ?"
}
return strings.TrimSuffix(v, "__lte") + columnEnclosure() + " <= ?"
}
if strings.HasSuffix(v, "__in") {
return strings.TrimSuffix(v, "__in") + columnEnclosure() + nTerm + " IN (?)"
}
if strings.HasSuffix(v, "__is") {
return strings.TrimSuffix(v, "__is") + columnEnclosure() + " IS" + nTerm + " NULL"
}
if strings.HasSuffix(v, "__contains") {
return strings.TrimSuffix(v, "__contains") + columnEnclosure() + nTerm + " " + getLike(true) + " ?"
}
if strings.HasSuffix(v, "__between") {
return strings.TrimSuffix(v, "__between") + columnEnclosure() + nTerm + " BETWEEN ? AND ?"
}
if strings.HasSuffix(v, "__startswith") {
if Database.Type == "mysql" {
return strings.TrimSuffix(v, "__startswith") + columnEnclosure() + nTerm + " " + getLike(true) + " ?"
} else if Database.Type == "sqlite" {
return strings.TrimSuffix(v, "__startswith") + columnEnclosure() + nTerm + " " + getLike(true) + " ?"
}
}
if strings.HasSuffix(v, "__endswith") {
if Database.Type == "mysql" {
return strings.TrimSuffix(v, "__endswith") + columnEnclosure() + nTerm + " " + getLike(true) + " ?"
} else if Database.Type == "sqlite" {
return strings.TrimSuffix(v, "__endswith") + columnEnclosure() + nTerm + " " + getLike(true) + " ?"
}
}
if strings.HasSuffix(v, "__re") {
return strings.TrimSuffix(v, "__re") + columnEnclosure() + nTerm + " REGEXP ?"
}
if strings.HasSuffix(v, "__icontains") {
return strings.TrimSuffix(v, "__icontains") + columnEnclosure() + nTerm + " " + getLike(false) + " ?"
}
if strings.HasSuffix(v, "__istartswith") {
return strings.TrimSuffix(v, "__istartswith") + columnEnclosure() + nTerm + " " + getLike(false) + " ?"
}
if strings.HasSuffix(v, "__iendswith") {
return strings.TrimSuffix(v, "__iendswith") + columnEnclosure() + nTerm + " " + getLike(false) + " ?"
}
if n {
return v + columnEnclosure() + " <> ?"
}
return v + columnEnclosure() + " = ?"
}
func getQueryArg(k, v string) []interface{} {
var err error
v, err = url.QueryUnescape(v)
if err != nil {
Trail(WARNING, "getQueryArg url.QueryUnescape unable to unescape value. %s", err)
return []interface{}{v}
}
if strings.HasSuffix(k, "__in") {
return []interface{}{strings.Split(v, ",")}
}
if strings.HasSuffix(k, "__is") {
// if strings.ToUpper(v) == "NULL" {
// return []interface{}{}
// }
return []interface{}{}
}
if strings.HasSuffix(k, "__contains") {
return []interface{}{"%" + v + "%"}
}
if strings.HasSuffix(k, "__between") {
splittedValue := strings.Split(v, ",")
from := splittedValue[0]
to := splittedValue[1]
return []interface{}{from, to}
}
if strings.HasSuffix(k, "__startswith") {
return []interface{}{v + "%"}
}
if strings.HasSuffix(k, "__endswith") {
return []interface{}{"%" + v}
}
if strings.HasSuffix(k, "__icontains") {
return []interface{}{"%" + v + "%"}
}
if strings.HasSuffix(k, "__istartswith") {
return []interface{}{v + "%"}
}
if strings.HasSuffix(k, "__iendswith") {
return []interface{}{"%" + v}
}
return []interface{}{v}
}
func getQueryFields(r *http.Request, params map[string]string, tableName string) (string, bool) {
//customSchema := false
fieldRaw, customSchema := params["$f"]
if fieldRaw == "" {
return "", customSchema
}
fieldParts := strings.Split(fieldRaw, ",")
fieldArray := []string{}
for _, field := range fieldParts {
// Check for SQL injection
if SQLInjection(r, field, "") {
continue
}
// Check for aggregation function
if strings.Contains(field, "__") {
//customSchema = true
fieldParts := strings.SplitN(field, "__", 2)
//add table name
if !strings.Contains(fieldParts[0], ".") {
fieldParts[0] = columnEnclosure() + tableName + columnEnclosure() + "." + columnEnclosure() + fieldParts[0] + columnEnclosure()
} else {
fieldNameParts := strings.Split(fieldParts[0], ".")
fieldParts[0] = columnEnclosure() + fieldNameParts[0] + columnEnclosure() + "." + columnEnclosure() + fieldNameParts[1] + columnEnclosure()
}
switch fieldParts[1] {
case "sum":
field = "SUM(" + fieldParts[0] + ") AS " + strings.Replace(field, ".", "__", -1)
case "min":
field = "MIN(" + fieldParts[0] + ") AS " + strings.Replace(field, ".", "__", -1)
case "max":
field = "MAX(" + fieldParts[0] + ") AS " + strings.Replace(field, ".", "__", -1)
case "avg":
field = "AVG(" + fieldParts[0] + ") AS " + strings.Replace(field, ".", "__", -1)
case "count":
field = "COUNT(" + fieldParts[0] + ") AS " + strings.Replace(field, ".", "__", -1)
case "date":
field = "DATE(" + fieldParts[0] + ") AS " + strings.Replace(field, ".", "__", -1)
case "year":
field = "YEAR(" + fieldParts[0] + ") AS " + strings.Replace(field, ".", "__", -1)
case "month":
field = "MONTH(" + fieldParts[0] + ") AS " + strings.Replace(field, ".", "__", -1)
case "day":
field = "DAY(" + fieldParts[0] + ") AS " + strings.Replace(field, ".", "__", -1)
}
} else {
//add table name
if !strings.Contains(field, ".") {
field = columnEnclosure() + tableName + columnEnclosure() + "." + columnEnclosure() + field + columnEnclosure()
} else {
fieldNameParts := strings.Split(field, ".")
if fieldNameParts[0] != tableName {
customSchema = true
}
field = columnEnclosure() + fieldNameParts[0] + columnEnclosure() + "." + columnEnclosure() + fieldNameParts[1] + columnEnclosure() + " AS " + strings.Replace(field, ".", "__", -1)
}
}
fieldArray = append(fieldArray, field)
}
return strings.Join(fieldArray, ", "), customSchema
}
func getQueryGroupBy(r *http.Request, params map[string]string) string {
groupByRaw := params["$groupby"]
if groupByRaw == "" {
return ""
}
groupByParts := strings.Split(groupByRaw, ",")
groupByArray := []string{}
for _, field := range groupByParts {
// Check for SQL injection
if SQLInjection(r, field, "") {
continue
}
groupByArray = append(groupByArray, field)
}
return strings.Join(groupByArray, ", ")
}
func getQueryOrder(r *http.Request, params map[string]string) string {
orderRaw := params["$order"]
if orderRaw == "" {
return ""
}
orderParts := strings.Split(orderRaw, ",")
orderArray := []string{}
for _, part := range orderParts {
if len(part) < 2 {
continue
}
if part[0] == '-' {
if SQLInjection(r, part[1:], "") {
continue
}
orderArray = append(orderArray, part[1:]+" desc")
} else {
if SQLInjection(r, part, "") {
continue
}
orderArray = append(orderArray, part)
}
}
return strings.Join(orderArray, ", ")
}
func getQueryLimit(r *http.Request, params map[string]string) string {
limitRaw := params["$limit"]
if SQLInjection(r, limitRaw, "") {
return ""
}
return limitRaw
}
func getQueryOffset(r *http.Request, params map[string]string) string {
offsetRaw := params["$offset"]
if SQLInjection(r, offsetRaw, "") {
return ""
}
return offsetRaw
}
func getQueryJoin(r *http.Request, params map[string]string, tableName string) string {
// $join syntax
// {} required
// [] optional
// $join={to_table_name}__[join_method]__{[from_table.]from_column}__[[to_table.]to_column]
joinType := map[string]string{
"inner": "INNER JOIN",
"outer": "FULL OUTER JOIN",
"left": "LEFT JOIN",
"right": "RIGHT JOIN",
}
join := params["$join"]
if join == "" {
return ""
}
joinList := strings.Split(join, ",")
joinFinalList := []string{}
joinTmpl := "{JOIN_METHOD} {TO_TABLE} ON {FROM_TABLE}.{FROM_COLUMN}={TO_TABLE}.{TO_COLUMN}"
for _, j := range joinList {
jParts := strings.Split(j, "__")
// Sanity Check
if len(jParts) < 2 {
continue
}
joinMethod := "INNER JOIN"
fromTable := tableName
toTable := jParts[0]
fromColumn := ""
toColumn := "id"
index := 1
// Check if the first part is a join method
for k, v := range joinType {
if k == jParts[index] {
joinMethod = v
index++
break
}
}
// Sanity Check
if index == 2 && len(jParts) < 3 {
continue
}
// Get from table/column
if strings.Contains(jParts[index], ".") {
fromParts := strings.Split(jParts[index], ".")
fromTable = fromParts[0]
fromColumn = fromParts[1]
} else {
fromColumn = jParts[index]
}
index++
// Check if there is a to table/column
if len(jParts) >= (index + 1) {
if strings.Contains(jParts[index], ".") {
toParts := strings.Split(jParts[index], ".")
toTable = toParts[0]
toColumn = toParts[1]
} else {
toColumn = jParts[index]
}
}
// Check for SQL injection
if SQLInjection(r, toTable, "") ||
SQLInjection(r, toColumn, "") ||
SQLInjection(r, fromTable, "") ||
SQLInjection(r, fromColumn, "") {
continue
}
// Build the Join statement
joinStm := strings.Replace(joinTmpl, "{JOIN_METHOD}", joinMethod, -1)
joinStm = strings.Replace(joinStm, "{TO_TABLE}", toTable, -1)
joinStm = strings.Replace(joinStm, "{TO_COLUMN}", toColumn, -1)
joinStm = strings.Replace(joinStm, "{FROM_TABLE}", fromTable, -1)
joinStm = strings.Replace(joinStm, "{FROM_COLUMN}", fromColumn, -1)
joinFinalList = append(joinFinalList, joinStm)
}
return strings.Join(joinFinalList, " ")
}
func getQueryM2M(params map[string]string, m interface{}, customSchema bool, modelName string) error {
// $m2m=0
// $m2m=$fill $m2m=1
// $m2m=$id
// $m2m=categories__fill
// $m2m=categories__id
// $m2m=categories__id,components__fill
// $m2m=categories__id,components__id
m2m := ""
fillType := ""
if params["$m2m"] == "" || params["$m2m"] == "fill" || params["$m2m"] == "1" {
m2m = "1"
fillType = "*"
} else if params["$m2m"] == "id" {
m2m = "1"
fillType = "id"
} else {
m2m = params["$m2m"]
}
// Check if M2M is not required
// TODO: Implement M2M for custom schema
if m2m == "0" || customSchema {
return nil
}
// Create a list of M2M
// SELECT `cards`.* FROM `cards` INNER JOIN `customer_card` ON `customer_card`.`table2_id`=`cards`.`id` WHERE `customer_card`.`table1_id` = 1
// SELECT `cards`.id FROM `cards` INNER JOIN `customer_card` ON `customer_card`.`table2_id`=`cards`.`id` WHERE `customer_card`.`table1_id` = 1
m2mTmpl := fixQueryEnclosure("SELECT `{TABLE_NAME}`.{FIELDS} FROM `{TABLE_NAME}` INNER JOIN `{M2M_TABLE_NAME}` ON `{M2M_TABLE_NAME}`.table2_id=`{TABLE_NAME}`.id WHERE `{M2M_TABLE_NAME}`.table1_id=? AND `{TABLE_NAME}`.deleted_at IS NULL")
m2mStmt := map[string]string{}
m2mModelName := map[string]string{}
s := Schema[modelName]
//table1 := s.TableName
table2 := ""
if m2m == "1" {
for _, f := range s.Fields {
if f.Type == cM2M {
table2 = Schema[strings.ToLower(f.TypeName)].TableName
m2mTable := s.ModelName + "_" + Schema[strings.ToLower(f.TypeName)].ModelName
m2mStmt[f.Name] = m2mTmpl
m2mStmt[f.Name] = strings.Replace(m2mStmt[f.Name], "{TABLE_NAME}", table2, -1)
m2mStmt[f.Name] = strings.Replace(m2mStmt[f.Name], "{FIELDS}", fillType, -1)
m2mStmt[f.Name] = strings.Replace(m2mStmt[f.Name], "{M2M_TABLE_NAME}", m2mTable, -1)
m2mModelName[f.Name] = Schema[strings.ToLower(f.TypeName)].ModelName
}
}
} else {
m2mList := strings.Split(m2m, ",")
for _, part := range m2mList {
m2mParts := strings.Split(part, "__")
if len(m2mParts) != 2 {
//Trail(WARNING, "DAPI: invalid m2m syntax: %s", part)
continue
}
if m2mParts[1] != "fill" && m2mParts[1] != "id" {
continue
} else if m2mParts[1] == "fill" {
m2mParts[1] = "*"
}
f := Schema[modelName].FieldByName(m2mParts[0])
table2Schema := Schema[strings.ToLower(f.TypeName)]
table2 = table2Schema.TableName
m2mTable := s.ModelName + "_" + table2Schema.ModelName
m2mStmt[f.Name] = m2mTmpl
m2mStmt[f.Name] = strings.Replace(m2mStmt[f.Name], "{TABLE_NAME}", table2, -1)
m2mStmt[f.Name] = strings.Replace(m2mStmt[f.Name], "{FIELDS}", m2mParts[1], -1)
m2mStmt[f.Name] = strings.Replace(m2mStmt[f.Name], "{M2M_TABLE_NAME}", m2mTable, -1)
m2mModelName[f.Name] = Schema[strings.ToLower(f.TypeName)].ModelName
}
}
mValue := reflect.ValueOf(m)
for i := 0; i < mValue.Elem().Len(); i++ {
for k, v := range m2mStmt {
tempList, _ := NewModelArray(m2mModelName[k], true)
GetDB().Raw(v, GetID(mValue.Elem().Index(i))).Scan(tempList.Interface())
mValue.Elem().Index(i).FieldByName(k).Set(tempList.Elem())
}
}
return nil
}
func returnDAPIJSON(w http.ResponseWriter, r *http.Request, a map[string]interface{}, params map[string]string, command string, model interface{}) error {
if params["$stat"] == "1" || params["$stat"] == "true" {
start := r.Context().Value(CKey("start"))
if start != nil {
sTime := start.(time.Time)
a["stats"] = map[string]interface{}{
"qtime": time.Since(sTime).String(),
}
}
}
if model != nil {
if command == "read" {
if APIPostQueryReadHandler != nil && !APIPostQueryReadHandler(w, r, a) {
return nil
}
if postQuery, ok := model.(APIPostQueryReader); ok {
if !postQuery.APIPostQueryRead(w, r, a) {
return nil
}
}
}
if command == "add" {
if APIPostQueryAddHandler != nil && !APIPostQueryAddHandler(w, r, a) {
return nil
}
if postQuery, ok := model.(APIPostQueryAdder); ok {
if !postQuery.APIPostQueryAdd(w, r, a) {
return nil
}
}
}
if command == "edit" {
if APIPostQueryEditHandler != nil && !APIPostQueryEditHandler(w, r, a) {
return nil
}
if postQuery, ok := model.(APIPostQueryEditor); ok {
if !postQuery.APIPostQueryEdit(w, r, a) {
return nil
}
}
}
if command == "delete" {
if APIPostQueryDeleteHandler != nil && !APIPostQueryDeleteHandler(w, r, a) {
return nil
}
if postQuery, ok := model.(APIPostQueryDeleter); ok {
if !postQuery.APIPostQueryDelete(w, r, a) {
return nil
}
}
}
if command == "schema" {
if postQuery, ok := model.(APIPostQuerySchemer); ok {
if !postQuery.APIPostQuerySchema(w, r, a) {
return nil
}
}
}
// if command == "method" {
/*
TODO: Add post query for methods
if postQuery, ok := model.(APIPostQueryMethoder); ok {
if !postQuery.APIPostQueryMethod(w, r, a) {
return nil
}
}
*/
// }
}
ReturnJSON(w, r, a)
return nil
}
// APILogReader is an interface for models to control logging their read function in dAPI
type APILogReader interface {
APILogRead(*http.Request) bool
}
// APILogEditor is an interface for models to control logging their edit function in dAPI
type APILogEditor interface {
APILogEdit(*http.Request) bool
}
// APILogAdder is an interface for models to control logging their add function in dAPI
type APILogAdder interface {
APILogAdd(*http.Request) bool
}
// APILogDeleter is an interface for models to control logging their delete function in dAPI
type APILogDeleter interface {
APILogDelete(*http.Request) bool
}
// APILogSchemer is an interface for models to control logging their schema function in dAPI
type APILogSchemer interface {
APILogSchema(*http.Request) bool
}
// APIPublicReader is an interface for models to control public access to read function in dAPI
type APIPublicReader interface {
APIPublicRead(*http.Request) bool
}
// APIPublicEditor is an interface for models to control public access to read function in dAPI
type APIPublicEditor interface {
APIPublicEdit(*http.Request) bool
}
// APIPublicAdder is an interface for models to control public access to add function in dAPI
type APIPublicAdder interface {
APIPublicAdd(*http.Request) bool
}
// APIPublicDeleter is an interface for models to control public access to delete function in dAPI
type APIPublicDeleter interface {
APIPublicDelete(*http.Request) bool
}
// APIPublicSchemer is an interface for models to control public access to schema function in dAPI
type APIPublicSchemer interface {
APIPublicSchema(*http.Request) bool
}
// APIDisabledReader is an interface for models to disable access to read function in dAPI
type APIDisabledReader interface {
APIDisabledRead(*http.Request) bool
}
// APIDisabledEditor is an interface for models to disable access to edit function in dAPI
type APIDisabledEditor interface {
APIDisabledEdit(*http.Request) bool
}
// APIDisabledAdder is an interface for models to disable access to add function in dAPI
type APIDisabledAdder interface {
APIDisabledAdd(*http.Request) bool
}
// APIDisabledDeleter is an interface for models to disable access to delete function in dAPI
type APIDisabledDeleter interface {
APIDisabledDelete(*http.Request) bool
}
// APIDisabledSchemer is an interface for models to disable access to schema function in dAPI
type APIDisabledSchemer interface {
APIDisabledSchema(*http.Request) bool
}
// APIPreQueryReader is an interface for models to run before processing read function in dAPI.
// Returning false stops the rest of the process from happening
type APIPreQueryReader interface {
APIPreQueryRead(http.ResponseWriter, *http.Request) bool
}
// APIPostQueryReader is an interface for models to run after processing read function in dAPI
// and before returning the results. Returning false stops the rest of the process from happening
type APIPostQueryReader interface {
APIPostQueryRead(http.ResponseWriter, *http.Request, map[string]interface{}) bool
}
// APIPreQueryAdder is an interface for models to run before processing add function in dAPI.
// Returning false stops the rest of the process from happening
type APIPreQueryAdder interface {
APIPreQueryAdd(http.ResponseWriter, *http.Request) bool
}
// APIPostQueryAdder is an interface for models to run after processing add function in dAPI
// and before returning the results. Returning false stops the rest of the process from happening
type APIPostQueryAdder interface {
APIPostQueryAdd(http.ResponseWriter, *http.Request, map[string]interface{}) bool
}
// APIPreQueryEditor is an interface for models to run before processing edit function in dAPI.
// Returning false stops the rest of the process from happening
type APIPreQueryEditor interface {
APIPreQueryEdit(http.ResponseWriter, *http.Request) bool
}
// APIPostQueryEditor is an interface for models to run after processing edit function in dAPI
// and before returning the results. Returning false stops the rest of the process from happening
type APIPostQueryEditor interface {
APIPostQueryEdit(http.ResponseWriter, *http.Request, map[string]interface{}) bool
}
// APIPreQueryDeleter is an interface for models to run before processing delete function in dAPI.
// Returning false stops the rest of the process from happening
type APIPreQueryDeleter interface {
APIPreQueryDelete(http.ResponseWriter, *http.Request) bool
}
// APIPostQueryDeleter is an interface for models to run after processing delete function in dAPI
// and before returning the results. Returning false stops the rest of the process from happening
type APIPostQueryDeleter interface {
APIPostQueryDelete(http.ResponseWriter, *http.Request, map[string]interface{}) bool
}
// APIPreQuerySchemer is an interface for models to run before processing schema function in dAPI.
// Returning false stops the rest of the process from happening
type APIPreQuerySchemer interface {
APIPreQuerySchema(http.ResponseWriter, *http.Request) bool
}
// APIPostQuerySchemer is an interface for models to run after processing schema function in dAPI
// and before returning the results. Returning false stops the rest of the process from happening
type APIPostQuerySchemer interface {
APIPostQuerySchema(http.ResponseWriter, *http.Request, map[string]interface{}) bool
}