guesstimate/server/internal/storm/provider.go

49 lines
931 B
Go
Raw Permalink Normal View History

package storm
import (
"reflect"
"github.com/asdine/storm/v3"
"github.com/pkg/errors"
"gitlab.com/wpetit/goweb/service"
)
func ServiceProvider(funcs ...OptionFunc) service.Provider {
opt := MergeOption(
DefaultOption(),
funcs...,
)
db, err := storm.Open(opt.Path)
if err == nil && opt.Objects != nil {
err = migrate(db, opt.Objects, opt.Init, opt.ReIndex)
}
return func(ctn *service.Container) (interface{}, error) {
if err != nil {
return nil, err
}
return db, nil
}
}
func migrate(db *storm.DB, objects []interface{}, init, reindex bool) error {
for _, o := range objects {
if init {
if err := db.Init(o); err != nil {
return errors.Wrapf(err, "could not init object '%s'", reflect.TypeOf(o).String())
}
}
if reindex {
if err := db.ReIndex(o); err != nil {
return errors.Wrapf(err, "could not reindex object '%s'", reflect.TypeOf(o).String())
}
}
}
return nil
}