package structmapper import ( "fmt" "sync" exception "git.apihub24.de/admin/exception" di "git.apihub24.de/admin/generic-di" ) func init() { di.Injectable(newMapperRegistry) } var ( MappingStrategyNotFound = exception.NewCustom("MappingStrategyNotFound") StrategyRuntimeException = exception.NewCustom("StrategyRuntimeException") ) func newMapperRegistry() *mapperRegistry { return &mapperRegistry{ strategies: map[string]func(any) (any, error){}, mu: sync.Mutex{}, } } type mapperRegistry struct { strategies map[string]func(any) (any, error) mu sync.Mutex } func (registry *mapperRegistry) Run(key string, value any) (any, error) { strategy, ok := registry.strategies[key] if !ok { return nil, MappingStrategyNotFound.With(fmt.Errorf("strategy key %s", key)) } var err error resultRef, err := strategy(value) if err != nil { return nil, StrategyRuntimeException.With(err) } return resultRef, nil } func (registry *mapperRegistry) RegisterStrategy(key string, strategy func(any) (any, error)) { registry.mu.Lock() defer registry.mu.Unlock() registry.strategies[key] = strategy } func (registry *mapperRegistry) UnregisterStrategy(key string) { registry.mu.Lock() defer registry.mu.Unlock() delete(registry.strategies, key) }