-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy patharray.go
92 lines (71 loc) · 2.02 KB
/
array.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
package schema
import (
"fmt"
"reflect"
"strconv"
)
type ArraySchema struct {
Schema[[]interface{}]
schema ISchema
}
var _ ISchema = (*ArraySchema)(nil)
func Array(s ISchema) *ArraySchema {
return &ArraySchema{schema: s}
}
func (s *ArraySchema) Max(maxLength int) *ArraySchema {
validator := Validator[[]interface{}]{
MessageFunc: func(value []interface{}) string {
return fmt.Sprintf("Array must contain at most %d element(s)", maxLength)
},
ValidateFunc: func(value []interface{}) bool {
return len(value) <= maxLength
},
}
s.validators = append(s.validators, validator)
return s
}
func (s *ArraySchema) Min(minLength int) *ArraySchema {
validator := Validator[[]interface{}]{
MessageFunc: func(value []interface{}) string {
return fmt.Sprintf("Array must contain at least %d element(s)", minLength)
},
ValidateFunc: func(value []interface{}) bool {
return len(value) >= minLength
},
}
s.validators = append(s.validators, validator)
return s
}
func (s *ArraySchema) Parse(value any) *ValidationResult {
t := reflect.TypeOf(value)
if t == nil || (t.Kind() != reflect.Array && t.Kind() != reflect.Slice) {
return &ValidationResult{Errors: []ValidationError{{Path: "", Message: fmt.Sprintf("Expected array, got %T", value)}}}
}
v := reflect.ValueOf(value)
val := make([]interface{}, v.Len())
for i := 0; i < v.Len(); i++ {
val[i] = v.Index(i).Interface()
}
// Parse array validations
result := &ValidationResult{Errors: []ValidationError{}}
for _, validator := range s.validators {
if !validator.ValidateFunc(val) {
err := ValidationError{
Path: "",
Message: validator.MessageFunc(val),
}
result.Errors = append(result.Errors, err)
}
}
// Parse schema validations within array for each item
for i := 0; i < len(val); i++ {
res := s.schema.Parse(val[i])
if !res.IsValid() {
for index, err := range res.Errors {
res.Errors[index].Path = formatPath(strconv.Itoa(i), err.Path)
}
result.Errors = append(result.Errors, res.Errors...)
}
}
return result
}