forked from miladibra10/vjson
/
object.go
73 lines (60 loc) · 1.52 KB
/
object.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
package vjson
import (
"encoding/json"
"github.com/pkg/errors"
)
// ObjectField is the type for validating another JSON object in a JSON
type ObjectField struct {
name string
required bool
schema Schema
}
// To Force Implementing Field interface by ObjectField
var _ Field = (*ObjectField)(nil)
// GetName returns name of the field
func (o *ObjectField) GetName() string {
return o.name
}
// GetType returns the Fields type
func (o *ObjectField) GetType() string {
return "object"
}
// GetRequired returns true if field is required
func (o *ObjectField) GetRequired() bool {
return o.required
}
// Validate is used for validating a value. it returns an error if the value is invalid.
func (o *ObjectField) Validate(v interface{}) error {
if v == nil {
if !o.required {
return nil
}
return errors.Errorf("Value for %s field is required", o.name)
}
// The input is either string or an interface{} object
value, ok := v.(string)
var err error
var jsonBytes []byte
if !ok {
jsonBytes, err = json.Marshal(v)
if err != nil {
return errors.Errorf("Value for %s should be an object", o.name)
}
} else {
return o.schema.ValidateString(value)
}
return o.schema.ValidateBytes(jsonBytes)
}
// Required is called to make a field required in a JSON
func (o *ObjectField) Required() *ObjectField {
o.required = true
return o
}
// Object is the constructor of an object field
func Object(name string, schema Schema) *ObjectField {
return &ObjectField{
name: name,
required: false,
schema: schema,
}
}