Use functional options

This commit is contained in:
Jinzhu 2021-03-04 17:14:08 +08:00
parent 3694ef4a2c
commit 0157099576
1 changed files with 30 additions and 11 deletions

41
gorm.go
View File

@ -56,6 +56,26 @@ type Config struct {
cacheStore *sync.Map cacheStore *sync.Map
} }
func (c *Config) Apply(config *Config) error {
return nil
}
func (c *Config) AfterInitialize(db *DB) error {
if db != nil {
for _, plugin := range c.Plugins {
if err := plugin.Initialize(db); err != nil {
return err
}
}
}
return nil
}
type Option interface {
Apply(*Config) error
AfterInitialize(*DB) error
}
// DB GORM DB definition // DB GORM DB definition
type DB struct { type DB struct {
*Config *Config
@ -83,9 +103,16 @@ type Session struct {
} }
// Open initialize db session based on dialector // Open initialize db session based on dialector
func Open(dialector Dialector, config *Config) (db *DB, err error) { func Open(dialector Dialector, opts ...Option) (db *DB, err error) {
if config == nil { config := &Config{}
config = &Config{}
for _, opt := range opts {
if opt != nil {
if err := opt.Apply(config); err != nil {
return nil, err
}
defer opt.AfterInitialize(db)
}
} }
if config.NamingStrategy == nil { if config.NamingStrategy == nil {
@ -106,14 +133,6 @@ func Open(dialector Dialector, config *Config) (db *DB, err error) {
if config.Plugins == nil { if config.Plugins == nil {
config.Plugins = map[string]Plugin{} config.Plugins = map[string]Plugin{}
} else {
for _, p := range config.Plugins {
defer func(plugin Plugin) {
if errr := plugin.Initialize(db); errr != nil {
err = errr
}
}(p)
}
} }
if config.cacheStore == nil { if config.cacheStore == nil {