-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbool.go
More file actions
60 lines (52 loc) · 1.2 KB
/
bool.go
File metadata and controls
60 lines (52 loc) · 1.2 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
package check
// BoolSchema validates boolean values.
type BoolSchema struct {
optional bool
defaultVal *bool
}
func NewBool() *BoolSchema {
return &BoolSchema{}
}
// clone returns a copy of this schema to preserve immutability in chains.
func (s *BoolSchema) clone() *BoolSchema {
copy := *s
return ©
}
func (s *BoolSchema) Optional() *BoolSchema {
s = s.clone()
s.optional = true
return s
}
func (s *BoolSchema) Default(v bool) *BoolSchema {
s = s.clone()
s.optional = true
s.defaultVal = &v
return s
}
func (s *BoolSchema) IsOptional() bool { return s.optional }
func (s *BoolSchema) Parse(value any) (any, error) {
errs := s.Validate(value)
if len(errs) > 0 {
return nil, ValidationErrors(errs)
}
if value == nil && s.defaultVal != nil {
return *s.defaultVal, nil
}
if value == nil {
return nil, nil
}
// Safe: Validate already confirmed it's a bool
return value.(bool), nil
}
func (s *BoolSchema) Validate(value any) []ValidationError {
if value == nil {
if s.optional {
return nil
}
return []ValidationError{{Message: "required value is missing"}}
}
if _, ok := value.(bool); !ok {
return []ValidationError{{Message: "expected bool", Value: value}}
}
return nil
}