ev/pkg/es/es.go

51 lines
986 B
Go
Raw Normal View History

2022-08-04 14:37:51 -06:00
package es
import (
"context"
"errors"
"fmt"
"strings"
"github.com/sour-is/ev/pkg/es/driver"
"github.com/sour-is/ev/pkg/locker"
)
type config struct {
drivers map[string]driver.Driver
}
var (
2022-08-06 09:52:36 -06:00
drivers = locker.New(&config{drivers: make(map[string]driver.Driver)})
2022-08-04 14:37:51 -06:00
)
2022-08-06 09:52:36 -06:00
func Register(ctx context.Context, name string, d driver.Driver) error {
return drivers.Modify(ctx, func(c *config) error {
2022-08-04 14:37:51 -06:00
if _, set := c.drivers[name]; set {
return fmt.Errorf("driver %s already set", name)
}
c.drivers[name] = d
return nil
})
}
func Open(ctx context.Context, dsn string) (driver.EventStore, error) {
name, _, ok := strings.Cut(dsn, ":")
if !ok {
return nil, fmt.Errorf("%w: no scheme", ErrNoDriver)
}
var d driver.Driver
2022-08-06 09:52:36 -06:00
drivers.Modify(ctx,func(c *config) error {
2022-08-04 14:37:51 -06:00
var ok bool
d, ok = c.drivers[name]
if !ok {
return fmt.Errorf("%w: %s not registered", ErrNoDriver, name)
}
return nil
})
return d.Open(dsn)
}
var ErrNoDriver = errors.New("no driver")