emissary/internal/spec/validator.go

51 lines
1.0 KiB
Go
Raw Permalink Normal View History

package spec
import (
"context"
"encoding/json"
"forge.cadoles.com/Cadoles/emissary/internal/datastore"
"github.com/pkg/errors"
"github.com/qri-io/jsonschema"
)
type Validator struct {
repo datastore.SpecDefinitionRepository
}
func (v *Validator) Validate(ctx context.Context, spec Spec) error {
name := spec.SpecDefinitionName()
version := spec.SpecDefinitionVersion()
if version == "" {
version = DefaultVersion
}
specDef, err := v.repo.Get(ctx, name, version)
if err != nil {
if errors.Is(err, datastore.ErrNotFound) {
return errors.WithStack(ErrUnknownSchema)
}
return errors.WithStack(err)
}
schema := &jsonschema.Schema{}
if err := json.Unmarshal(specDef.Schema, schema); err != nil {
return errors.WithStack(err)
}
state := schema.Validate(ctx, map[string]any(spec.SpecData()))
if !state.IsValid() {
return errors.WithStack(&ValidationError{*state.Errs})
}
return nil
}
func NewValidator(repo datastore.SpecDefinitionRepository) *Validator {
return &Validator{
repo: repo,
}
}