generated from sv-tools/go-repo-template
-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathbool_or_schema.go
84 lines (74 loc) · 1.71 KB
/
bool_or_schema.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
package openapi
import (
"encoding/json"
"gopkg.in/yaml.v3"
)
// BoolOrSchema handles Boolean or Schema type.
//
// It MUST be used as a pointer,
// otherwise the `false` can be omitted by json or yaml encoders in case of `omitempty` tag is set.
type BoolOrSchema struct {
Schema *RefOrSpec[Schema]
Allowed bool
}
// UnmarshalJSON implements json.Unmarshaler interface.
func (o *BoolOrSchema) UnmarshalJSON(data []byte) error {
if json.Unmarshal(data, &o.Allowed) == nil {
o.Schema = nil
return nil
}
if err := json.Unmarshal(data, &o.Schema); err != nil {
return err
}
o.Allowed = true
return nil
}
// MarshalJSON implements json.Marshaler interface.
func (o *BoolOrSchema) MarshalJSON() ([]byte, error) {
var v any
if o.Schema != nil {
v = o.Schema
} else {
v = o.Allowed
}
return json.Marshal(&v)
}
// UnmarshalYAML implements yaml.Unmarshaler interface.
func (o *BoolOrSchema) UnmarshalYAML(node *yaml.Node) error {
if node.Decode(&o.Allowed) == nil {
o.Schema = nil
return nil
}
if err := node.Decode(&o.Schema); err != nil {
return err
}
o.Allowed = true
return nil
}
// MarshalYAML implements yaml.Marshaler interface.
func (o *BoolOrSchema) MarshalYAML() (any, error) {
var v any
if o.Schema != nil {
v = o.Schema
} else {
v = o.Allowed
}
return v, nil
}
func (o *BoolOrSchema) validateSpec(path string, validator *Validator) []*validationError {
var errs []*validationError
if o.Schema != nil {
errs = append(errs, o.Schema.validateSpec(path, validator)...)
}
return errs
}
func NewBoolOrSchema(v any) *BoolOrSchema {
switch v := v.(type) {
case bool:
return &BoolOrSchema{Allowed: v}
case *RefOrSpec[Schema]:
return &BoolOrSchema{Schema: v}
default:
return nil
}
}