84 lines
1.9 KiB
Go
84 lines
1.9 KiB
Go
package inputregistry
|
|
|
|
import (
|
|
"fmt"
|
|
"sort"
|
|
"strings"
|
|
|
|
"gitea.maximumdirect.net/eric/notarius/internal/framework/contracts"
|
|
)
|
|
|
|
type Constructor func() (contracts.InputAdapter, error)
|
|
|
|
type Registry struct {
|
|
constructors map[string]Constructor
|
|
}
|
|
|
|
func New() *Registry {
|
|
return &Registry{
|
|
constructors: make(map[string]Constructor),
|
|
}
|
|
}
|
|
|
|
func (r *Registry) Register(key string, constructor Constructor) error {
|
|
if r == nil {
|
|
return fmt.Errorf("input adapter registry must not be nil")
|
|
}
|
|
|
|
normalizedKey := strings.TrimSpace(key)
|
|
if normalizedKey == "" {
|
|
return fmt.Errorf("input adapter key must not be empty")
|
|
}
|
|
if constructor == nil {
|
|
return fmt.Errorf("input adapter constructor for %q must not be nil", normalizedKey)
|
|
}
|
|
if _, ok := r.constructors[normalizedKey]; ok {
|
|
return fmt.Errorf("input adapter %q is already registered", normalizedKey)
|
|
}
|
|
|
|
r.constructors[normalizedKey] = constructor
|
|
return nil
|
|
}
|
|
|
|
func (r *Registry) Build(key string) (contracts.InputAdapter, error) {
|
|
if r == nil {
|
|
return nil, fmt.Errorf("input adapter registry must not be nil")
|
|
}
|
|
|
|
normalizedKey := strings.TrimSpace(key)
|
|
if normalizedKey == "" {
|
|
return nil, fmt.Errorf("input adapter key must not be empty")
|
|
}
|
|
|
|
constructor, ok := r.constructors[normalizedKey]
|
|
if !ok {
|
|
return nil, fmt.Errorf("input adapter %q is not registered", normalizedKey)
|
|
}
|
|
|
|
adapter, err := constructor()
|
|
if err != nil {
|
|
return nil, fmt.Errorf("build input adapter %q: %w", normalizedKey, err)
|
|
}
|
|
if adapter == nil {
|
|
return nil, fmt.Errorf("input adapter %q constructor returned nil", normalizedKey)
|
|
}
|
|
if adapter.Key() != normalizedKey {
|
|
return nil, fmt.Errorf("input adapter %q returned key %q", normalizedKey, adapter.Key())
|
|
}
|
|
|
|
return adapter, nil
|
|
}
|
|
|
|
func (r *Registry) RegisteredKeys() []string {
|
|
if r == nil {
|
|
return nil
|
|
}
|
|
|
|
keys := make([]string, 0, len(r.constructors))
|
|
for key := range r.constructors {
|
|
keys = append(keys, key)
|
|
}
|
|
sort.Strings(keys)
|
|
return keys
|
|
}
|