emissary/internal/spec/registry.go
William Petit f612721b4e
All checks were successful
arcad/emissary/pipeline/head This commit looks good
arcad/emissary/pipeline/pr-master This commit looks good
feat: add spec definition api with versioning
2024-03-12 16:22:35 +01:00

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
}