64 lines
1.3 KiB
Go
64 lines
1.3 KiB
Go
package spec
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
|
|
"github.com/pkg/errors"
|
|
"github.com/qri-io/jsonschema"
|
|
)
|
|
|
|
type Validator struct {
|
|
schemas map[Name]*jsonschema.Schema
|
|
}
|
|
|
|
func (v *Validator) Register(name Name, rawSchema []byte) error {
|
|
schema := &jsonschema.Schema{}
|
|
if err := json.Unmarshal(rawSchema, schema); err != nil {
|
|
return errors.Wrapf(err, "could not register spec shema '%s'", name)
|
|
}
|
|
|
|
v.schemas[name] = schema
|
|
|
|
return nil
|
|
}
|
|
|
|
func (v *Validator) Validate(ctx context.Context, spec Spec) (bool, error) {
|
|
schema, exists := v.schemas[spec.SpecName()]
|
|
if !exists {
|
|
return false, errors.WithStack(ErrUnknownSchema)
|
|
}
|
|
|
|
state := schema.Validate(ctx, spec.SpecData())
|
|
if !state.IsValid() {
|
|
return false, errors.WithStack(&ValidationError{*state.Errs})
|
|
}
|
|
|
|
return true, nil
|
|
}
|
|
|
|
func NewValidator() *Validator {
|
|
return &Validator{
|
|
schemas: make(map[Name]*jsonschema.Schema),
|
|
}
|
|
}
|
|
|
|
var defaultValidator = NewValidator()
|
|
|
|
func Register(name Name, rawSchema []byte) error {
|
|
if err := defaultValidator.Register(name, rawSchema); err != nil {
|
|
return errors.WithStack(err)
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
func Validate(ctx context.Context, spec Spec) (bool, error) {
|
|
ok, err := defaultValidator.Validate(ctx, spec)
|
|
if err != nil {
|
|
return ok, errors.WithStack(err)
|
|
}
|
|
|
|
return ok, nil
|
|
}
|