Skip to content

Commit

Permalink
feat(validation.go): add ValidateSchema function (#256)
Browse files Browse the repository at this point in the history
Signed-off-by: Vaughn Dice <vadice@microsoft.com>
  • Loading branch information
vdice committed May 27, 2021
1 parent 9face0e commit c9cd200
Showing 1 changed file with 19 additions and 8 deletions.
27 changes: 19 additions & 8 deletions bundle/definition/validation.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"encoding/json"

"github.com/pkg/errors"
"github.com/qri-io/jsonschema"
)

// ValidationError error represents a validation error
Expand All @@ -14,20 +15,30 @@ type ValidationError struct {
Error string
}

// Validate applies JSON Schema validation to the data passed as a parameter.
// If validation errors occur, they will be returned in as a slice of ValidationError
// structs. If any other error occurs, it will be returned as a separate error
func (s *Schema) Validate(data interface{}) ([]ValidationError, error) {

// ValidateSchema validates that the Schema is valid JSON Schema.
// If no errors occur, the validated jsonschema.Schema is returned.
func (s *Schema) ValidateSchema() (*jsonschema.RootSchema, error) {
b, err := json.Marshal(s)
if err != nil {
return nil, errors.Wrap(err, "unable to load schema")
}
def := NewRootSchema()
err = json.Unmarshal([]byte(b), def)
rs := NewRootSchema()
err = rs.UnmarshalJSON(b)
if err != nil {
return nil, errors.Wrap(err, "schema not valid")
}
return rs, nil
}

// Validate applies JSON Schema validation to the data passed as a parameter.
// If validation errors occur, they will be returned in as a slice of ValidationError
// structs. If any other error occurs, it will be returned as a separate error
func (s *Schema) Validate(data interface{}) ([]ValidationError, error) {
def, err := s.ValidateSchema()
if err != nil {
return nil, errors.Wrap(err, "unable to build schema")
return nil, err
}

payload, err := json.Marshal(data)
if err != nil {
return nil, errors.Wrap(err, "unable to process data")
Expand Down

0 comments on commit c9cd200

Please sign in to comment.