-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtime.go
109 lines (84 loc) · 2.21 KB
/
time.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
package owl
import (
"encoding/json"
"errors"
"fmt"
"reflect"
"time"
)
type TimeSchema struct {
schema *AnySchema
layout string
}
func Time() *TimeSchema {
self := &TimeSchema{Any(), time.RFC3339}
self.Rule("type", self.Type(), func(value reflect.Value) (any, error) {
if !value.IsValid() {
return nil, nil
}
if value.Kind() != reflect.String && value.Type() != reflect.TypeFor[time.Time]() {
return value.Interface(), errors.New("must be a string or time.Time")
}
if value.Kind() == reflect.String {
parsed, err := time.Parse(self.layout, value.String())
if err != nil {
return value.Interface(), err
}
value = reflect.ValueOf(parsed)
}
return value.Interface(), nil
})
return self
}
func (self TimeSchema) Type() string {
return "time"
}
func (self *TimeSchema) Layout(layout string) *TimeSchema {
self.layout = layout
return self
}
func (self *TimeSchema) Rule(key string, value any, rule RuleFn) *TimeSchema {
self.schema.Rule(key, value, rule)
return self
}
func (self *TimeSchema) Message(message string) *TimeSchema {
self.schema.Message(message)
return self
}
func (self *TimeSchema) Required() *TimeSchema {
self.schema.Required()
return self
}
func (self *TimeSchema) Min(min time.Time) *TimeSchema {
return self.Rule("min", min, func(value reflect.Value) (any, error) {
if !value.IsValid() {
return nil, nil
}
parsed := value.Interface().(time.Time)
if parsed.Before(min) {
return parsed, fmt.Errorf("must have value of at least %s", min.String())
}
return parsed, nil
})
}
func (self *TimeSchema) Max(max time.Time) *TimeSchema {
return self.Rule("max", max, func(value reflect.Value) (any, error) {
if !value.IsValid() {
return nil, nil
}
parsed := value.Interface().(time.Time)
if parsed.After(max) {
return parsed, fmt.Errorf("must have value of at most %s", max.String())
}
return parsed, nil
})
}
func (self TimeSchema) MarshalJSON() ([]byte, error) {
return json.Marshal(self.schema)
}
func (self TimeSchema) Validate(value any) error {
return self.validate("", reflect.Indirect(reflect.ValueOf(value)))
}
func (self TimeSchema) validate(key string, value reflect.Value) error {
return self.schema.validate(key, value)
}