53 lines
1.5 KiB
Go
53 lines
1.5 KiB
Go
|
|
// Package sharedglossary implements the boundary for shared glossary documents.
|
||
|
|
package sharedglossary
|
||
|
|
|
||
|
|
import (
|
||
|
|
_ "embed"
|
||
|
|
"encoding/json"
|
||
|
|
"fmt"
|
||
|
|
|
||
|
|
"github.com/santhosh-tekuri/jsonschema/v6"
|
||
|
|
)
|
||
|
|
|
||
|
|
const schemaID = "https://schemas.maximumdirect.net/glossary/v0.2.0/schema.json"
|
||
|
|
|
||
|
|
//go:embed assets/glossary/v0.2.0/schema.json
|
||
|
|
var schemaData []byte
|
||
|
|
|
||
|
|
// Validator validates completed shared glossary envelopes.
|
||
|
|
type Validator struct {
|
||
|
|
schema *jsonschema.Schema
|
||
|
|
}
|
||
|
|
|
||
|
|
// NewValidator compiles the locally bundled schema for reuse.
|
||
|
|
func NewValidator() (*Validator, error) {
|
||
|
|
var document any
|
||
|
|
if err := json.Unmarshal(schemaData, &document); err != nil {
|
||
|
|
return nil, fmt.Errorf("decode shared glossary schema: %w", err)
|
||
|
|
}
|
||
|
|
compiler := jsonschema.NewCompiler()
|
||
|
|
compiler.UseLoader(offlineLoader{})
|
||
|
|
if err := compiler.AddResource(schemaID, document); err != nil {
|
||
|
|
return nil, fmt.Errorf("register shared glossary schema: %w", err)
|
||
|
|
}
|
||
|
|
schema, err := compiler.Compile(schemaID)
|
||
|
|
if err != nil {
|
||
|
|
return nil, fmt.Errorf("compile shared glossary schema: %w", err)
|
||
|
|
}
|
||
|
|
return &Validator{schema: schema}, nil
|
||
|
|
}
|
||
|
|
|
||
|
|
// Validate checks an envelope without modifying it, retaining source context.
|
||
|
|
func (v *Validator) Validate(document map[string]any, source string) error {
|
||
|
|
if err := v.schema.Validate(document); err != nil {
|
||
|
|
return fmt.Errorf("shared glossary %s: %w", source, err)
|
||
|
|
}
|
||
|
|
return nil
|
||
|
|
}
|
||
|
|
|
||
|
|
type offlineLoader struct{}
|
||
|
|
|
||
|
|
func (offlineLoader) Load(url string) (any, error) {
|
||
|
|
return nil, fmt.Errorf("unregistered schema resource %q", url)
|
||
|
|
}
|