/
factory.go
62 lines (44 loc) · 1.01 KB
/
factory.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
package json
import (
"errors"
"github.com/project-flogo/core/data/schema"
"github.com/xeipuuv/gojsonschema"
)
func init() {
_ = schema.RegisterFactory("json", &factory{})
}
type factory struct {
}
func (factory) New(def *schema.Def) (schema.Schema, error) {
schemaLoader := gojsonschema.NewStringLoader(string(def.Value))
s, err := gojsonschema.NewSchema(schemaLoader)
if err != nil {
return nil, err
}
return &jsonSchema{def: def, js: s}, nil
}
type jsonSchema struct {
def *schema.Def
js *gojsonschema.Schema
}
func (s *jsonSchema) Type() string {
return s.def.Type
}
func (s *jsonSchema) Value() string {
return s.def.Value
}
func (s *jsonSchema) Validate(data interface{}) error {
loader := gojsonschema.NewGoLoader(data)
r, err := s.js.Validate(loader)
if err != nil {
return err
}
if !r.Valid() {
var errs []error
for _, err := range r.Errors() {
errs = append(errs, errors.New(err.String()))
}
return schema.NewValidationError("validation failed", errs)
}
return nil
}