-
Notifications
You must be signed in to change notification settings - Fork 0
/
int.go
103 lines (80 loc) · 2.03 KB
/
int.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
package owl
import (
"encoding/json"
"errors"
"fmt"
"reflect"
)
type IntSchema struct {
schema *AnySchema
}
func Int() *IntSchema {
self := &IntSchema{Any()}
self.Rule("type", self.Type(), func(value reflect.Value) (any, error) {
if !value.IsValid() {
return nil, nil
}
if value.CanConvert(reflect.TypeFor[int]()) {
value = value.Convert(reflect.TypeFor[int]())
}
if value.Kind() != reflect.Int {
return value.Interface(), errors.New("must be an int")
}
return value.Interface(), nil
})
return self
}
func (self IntSchema) Type() string {
return "int"
}
func (self *IntSchema) Rule(key string, value any, rule RuleFn) *IntSchema {
self.schema.Rule(key, value, rule)
return self
}
func (self *IntSchema) Message(message string) *IntSchema {
self.schema.Message(message)
return self
}
func (self *IntSchema) Required() *IntSchema {
self.schema.Required()
return self
}
func (self *IntSchema) Enum(values ...int) *IntSchema {
newValues := make([]any, len(values))
for i, value := range values {
newValues[i] = value
}
self.schema.Enum(newValues...)
return self
}
func (self *IntSchema) Min(min int) *IntSchema {
return self.Rule("min", min, func(value reflect.Value) (any, error) {
if !value.IsValid() {
return nil, nil
}
if value.Int() < int64(min) {
return value.Interface(), fmt.Errorf("must have value of at least %d", min)
}
return value.Interface(), nil
})
}
func (self *IntSchema) Max(max int) *IntSchema {
return self.Rule("max", max, func(value reflect.Value) (any, error) {
if !value.IsValid() {
return nil, nil
}
if value.Int() > int64(max) {
return value.Interface(), fmt.Errorf("must have value of at most %d", max)
}
return value.Interface(), nil
})
}
func (self IntSchema) MarshalJSON() ([]byte, error) {
return json.Marshal(self.schema)
}
func (self IntSchema) Validate(value any) error {
return self.validate("", reflect.ValueOf(value))
}
func (self IntSchema) validate(key string, value reflect.Value) error {
return self.schema.validate(key, value)
}