-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathrule_builder.go
302 lines (269 loc) · 6.58 KB
/
rule_builder.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
package xvalid
import (
"encoding/json"
"errors"
"reflect"
"strings"
)
// Error when a rule is broken
type Error interface {
Error() string
Field() []string
}
// validationError implements Error interface
type validationError struct {
message string
field []string
}
// Error message
func (v validationError) Error() string {
return v.message
}
// Field name
func (v validationError) Field() []string {
return v.field
}
func (e validationError) MarshalJSON() ([]byte, error) {
// only use the last field name for embeded structs
return json.MarshalIndent(struct {
Message string `json:"message"`
FieldName string `json:"field"`
}{e.message, jsonFieldName(e.field)}, "", " ")
}
// NewError creates new validation error
func NewError(message string, field... string) Error {
return &validationError{
field: field,
message: message,
}
}
// ErrorSlice is a list of Error
type ErrorSlice []Error
// Error will combine all errors into a list of sentences
func (e ErrorSlice) Error() string {
list := make([]string, len(e))
for i := range e {
list[i] = e[i].Error()
}
return joinSentences(list)
}
// Unwrap errors
func (e ErrorSlice) Unwrap() []error {
errs := make([]error, len(e))
for i := range e {
errs[i] = e[i]
}
return errs
}
// ToMap converts to map
func (e ErrorSlice) ToMap() ErrorMap {
errs := make(ErrorMap)
for i, err := range e {
errs[jsonFieldName(err.Field())] = e[i]
}
return errs
}
// ErrorMap is a map of Error
type ErrorMap map[string]Error
// Error will combine all errors into a list of sentences
func (e ErrorMap) Error() string {
list := make([]string, 0)
for _, err := range e {
list = append(list, err.Error())
}
return joinSentences(list)
}
// Unwrap errors
func (e ErrorMap) Unwrap() []error {
errs := make([]error, 0)
for _, err := range e {
errs = append(errs, err)
}
return errs
}
// ToSlice converts to slice
func (e ErrorMap) ToSlice() ErrorSlice {
errs := make(ErrorSlice, 0)
for _, err := range e {
errs = append(errs, err)
}
return errs
}
func (e ErrorMap) MarshalJSON() ([]byte, error) {
m := make(map[string]string)
for k, v := range e {
m[k] = v.Error()
}
return json.Marshal(m)
}
// -----
// Validator to implement a rule
type Validator interface {
SetField(...string)
Field() []string
CanExport() bool
SetMessage(string) Validator
Validate(any) Error
}
// Rules for creating a chain of rules for validating a struct
type Rules struct {
validators []Validator
structPtr any
}
// New rule chain
func New(structPtr any) Rules {
return Rules{
structPtr: structPtr,
validators: make([]Validator, 0),
}
}
// Field adds validators for a field
func (r Rules) Field(fieldPtr any, validators ...Validator) Rules {
for _, validator := range validators {
validator.SetField(getField(r.structPtr, fieldPtr)...)
r.validators = append(r.validators, validator)
}
return r
}
// Struct adds validators for the struct
func (r Rules) Struct(validators ...Validator) Rules {
r.validators = append(r.validators, validators...)
return r
}
// Validate a struct and return Errors
func (r Rules) Validate(subject any) error {
errs := make(ErrorSlice, 0)
vmap := structToMap(subject)
for _, validator := range r.validators {
var err Error
if validator.Field() == nil || len(validator.Field()) == 0 {
// struct validation
err = validator.Validate(subject)
} else {
// field validation
v := vmap
for _, p := range validator.Field() {
switch v2 := v[p].(type) {
default:
err = validator.Validate(v2)
case map[string]any:
v = v2
}
}
}
if err != nil {
errs = append(errs, err)
}
}
if len(errs) > 0 {
return errs
}
return nil
}
// Validators for this chain
func (r Rules) Validators() []Validator {
return r.validators
}
func (r Rules) MarshalJSON() ([]byte, error) {
rmap := make(map[string][]any)
validators := r.Validators()
for _, v := range validators {
if !v.CanExport() {
continue
}
name := jsonFieldName(v.Field())
rules, ok := rmap[name]
if !ok {
rules = make([]any, 0)
}
rules = append(rules, v)
rmap[name] = rules
}
return json.MarshalIndent(rmap, "", " ")
}
// -------------------
func getField(structPtr any, fieldPtr any) []string {
value := reflect.ValueOf(structPtr)
if value.Kind() != reflect.Ptr || !value.IsNil() && value.Elem().Kind() != reflect.Struct {
panic(errors.New("struct is not pointer"))
}
if value.IsNil() {
panic(errors.New("struct is nil"))
}
value = value.Elem()
fv := reflect.ValueOf(fieldPtr)
if fv.Kind() != reflect.Ptr {
panic(errors.New("field is not pointer"))
}
fields := findStructField(value, fv, make([]*reflect.StructField, 0))
if len(fields) == 0 {
panic(errors.New("can't find field"))
}
parts := make([]string, 0)
for _, f := range fields {
tag := strings.Split(f.Tag.Get("json"), ",")[0]
if tag == "" {
tag = f.Name
}
parts = append(parts, tag)
}
return parts
}
// findStructField looks for a field in the given struct.
// The field being looked for should be a pointer to the actual struct field.
// If found, the fields will be returned. Otherwise, an empty list will be returned.
func findStructField(structValue reflect.Value, fieldValue reflect.Value, results []*reflect.StructField) []*reflect.StructField {
ptr := fieldValue.Pointer()
depth := len(results)
for i := structValue.NumField() - 1; i >= 0; i-- {
sf := structValue.Type().Field(i)
if ptr == structValue.Field(i).UnsafeAddr() {
if sf.Anonymous {
return findStructField(structValue.Field(i), fieldValue, append(results, &sf))
}
return append(results, &sf)
} else if sf.Anonymous {
tmp := findStructField(structValue.Field(i), fieldValue, append(results, &sf))
if len(tmp) > depth+1 {
return tmp
}
}
}
return results
}
// joinSentences converts a list of strings to a paragraph
func joinSentences(list []string) string {
l := len(list)
if l == 0 {
return ""
}
return strings.Join(list, ". ") + "."
}
// structToMap converts struct to map and uses the json name if available
func structToMap(structPtr any) map[string]any {
vmap := make(map[string]any)
structValue := reflect.ValueOf(structPtr)
for i := structValue.NumField() - 1; i >= 0; i-- {
sf := structValue.Type().Field(i)
name := strings.Split(sf.Tag.Get("json"), ",")[0]
if name == "" {
name = sf.Name
}
f := structValue.Field(i)
if f.CanInterface() {
if sf.Anonymous {
vmap[name] = structToMap(f.Interface())
} else {
vmap[name] = f.Interface()
}
}
}
return vmap
}
// jsonFieldName returns the last field name
func jsonFieldName(field []string) string {
if field == nil {
return ""
}
return field[len(field)-1]
}