67 lines
1.4 KiB
Go
67 lines
1.4 KiB
Go
package spec
|
|
|
|
import (
|
|
"encoding/json"
|
|
|
|
"github.com/pkg/errors"
|
|
"github.com/qri-io/jsonschema"
|
|
)
|
|
|
|
type Registry struct {
|
|
definitions map[string]map[string][]byte
|
|
}
|
|
|
|
func (r *Registry) Register(name string, version string, schema []byte) error {
|
|
// Assert that provided schema is valid
|
|
if err := json.Unmarshal(schema, &jsonschema.Schema{}); err != nil {
|
|
return errors.WithStack(err)
|
|
}
|
|
|
|
specDefinitions, exists := r.definitions[name]
|
|
if !exists {
|
|
specDefinitions = make(map[string][]byte)
|
|
}
|
|
|
|
specDefinitions[version] = schema
|
|
|
|
r.definitions[name] = specDefinitions
|
|
|
|
return nil
|
|
}
|
|
|
|
func (r *Registry) Walk(fn func(name string, version string, schema []byte) error) error {
|
|
for name, specDefinitions := range r.definitions {
|
|
for version, schema := range specDefinitions {
|
|
if err := fn(name, version, schema); err != nil {
|
|
return errors.WithStack(err)
|
|
}
|
|
}
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
func NewRegistry() *Registry {
|
|
return &Registry{
|
|
definitions: make(map[string]map[string][]byte),
|
|
}
|
|
}
|
|
|
|
var defaultRegistry = NewRegistry()
|
|
|
|
func Register(name string, version string, schema []byte) error {
|
|
if err := defaultRegistry.Register(name, version, schema); err != nil {
|
|
return errors.WithStack(err)
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
func Walk(fn func(name string, version string, schema []byte) error) error {
|
|
if err := defaultRegistry.Walk(fn); err != nil {
|
|
return errors.WithStack(err)
|
|
}
|
|
|
|
return nil
|
|
}
|