Core

/app/util/fielddesc.go (2.6 KB)

  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
package util

import (
"net/http"

"github.com/pkg/errors"
"github.com/samber/lo"
)

type FieldDesc struct {
Key string `json:"key"`
Title string `json:"title"`
Description string `json:"description,omitzero"`
Type string `json:"type,omitzero"`
Default string `json:"default,omitzero"`
Choices []string `json:"choices,omitempty"`
}

func (d *FieldDesc) Parse(q any) (any, error) {
switch d.Type {
case "bool", "boolean":
return ParseBool(q, "", true)
case "float":
return ParseFloat(q, "", true)
case "int", "number":
return ParseInt(q, "", true)
case "int64", "bigint":
return ParseInt64(q, "", true)
case "string", "":
return ParseString(q, "", true)
case "[]string":
return ParseArrayString(q, "", true)
case "time":
return ParseTime(q, "", true)
default:
return nil, errors.Errorf("unable to parse [%s] value from string [%s]", d.Type, q)
}
}

func (d *FieldDesc) TitleSafe() string {
if d.Title != "" {
return d.Title
}
return d.Key
}

func (d *FieldDesc) DefaultBool() bool {
if d.Default != "" {
return ParseBoolSimple(d.Default)
}
return false
}

func (d *FieldDesc) DefaultInt() int {
if d.Default != "" {
return ParseIntSimple(d.Default)
}
return 0
}

func (d *FieldDesc) DefaultFloat() float64 {
if d.Default != "" {
return ParseFloatSimple(d.Default)
}
return 0
}

type FieldDescs []*FieldDesc

func (d FieldDescs) Get(key string) *FieldDesc {
return lo.FindOrElse(d, nil, func(x *FieldDesc) bool {
return x.Key == key
})
}

func (d FieldDescs) Keys() []string {
return lo.Map(d, func(x *FieldDesc, _ int) string {
return x.Key
})
}

type FieldDescResults struct {
FieldDescs FieldDescs `json:"fieldDescs"`
Values ValueMap `json:"values"`
Missing []string `json:"missing,omitempty"`
}

func (a *FieldDescResults) HasMissing() bool {
return len(a.Missing) > 0
}

func FieldDescsCollect(r *http.Request, args FieldDescs) *FieldDescResults {
qa := r.URL.Query()
m := ValueMap{}
lo.ForEach(args, func(arg *FieldDesc, _ int) {
if qa.Has(arg.Key) {
m[arg.Key] = qa.Get(arg.Key)
}
})
return FieldDescsCollectMap(m, args)
}

func FieldDescsCollectMap(m ValueMap, args FieldDescs) *FieldDescResults {
ret := make(ValueMap, len(args))
var missing []string
lo.ForEach(args, func(arg *FieldDesc, _ int) {
if m.HasKey(arg.Key) {
ret[arg.Key] = m[arg.Key]
} else {
missing = append(missing, arg.Key)
if arg.Default != "" {
ret[arg.Key] = arg.Default
}
}
})
return &FieldDescResults{FieldDescs: args, Values: ret, Missing: missing}
}