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) error { schema, exists := v.schemas[spec.SpecName()] if !exists { return errors.WithStack(ErrUnknownSchema) } state := schema.Validate(ctx, map[string]any(spec.SpecData())) if !state.IsValid() { return errors.WithStack(&ValidationError{*state.Errs}) } return 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) error { if err := defaultValidator.Validate(ctx, spec); err != nil { return errors.WithStack(err) } return nil }