gorm db openned in options

This commit is contained in:
Adphi 2020-03-03 14:54:53 +01:00
parent 3375b4f379
commit ac9a81d3e7
2 changed files with 14 additions and 2 deletions

View File

@ -144,9 +144,11 @@ func WithKey(path string) Option {
}
}
func WithDB(db *gorm.DB) Option {
func WithDB(dialect string, args ...interface{}) Option {
db, err := gorm.Open(dialect, args...)
return func(o *options) {
o.db = db
o.error = err
}
}
@ -236,6 +238,8 @@ type options struct {
clientInterceptors []grpc.UnaryClientInterceptor
streamClientInterceptors []grpc.StreamClientInterceptor
error error
}
func (o *options) Name() string {

View File

@ -8,6 +8,7 @@ import (
grpcmiddleware "github.com/grpc-ecosystem/go-grpc-middleware"
"github.com/jinzhu/gorm"
"github.com/spf13/cobra"
"go.uber.org/multierr"
"google.golang.org/grpc"
)
@ -45,6 +46,9 @@ func newService(opts ...Option) (*service, error) {
for _, f := range opts {
f(s.opts)
}
if s.opts.error != nil {
return nil, s.opts.error
}
go func() {
for {
select {
@ -144,5 +148,9 @@ func (s *service) Stop() error {
func (s *service) Close() error {
s.mu.Lock()
defer s.mu.Unlock()
return s.Stop()
err := multierr.Combine(s.Stop())
if s.opts.db != nil {
err = multierr.Append(s.opts.db.Close(), err)
}
return err
}