mirror of https://github.com/go-gorm/gorm.git
Use functional options
This commit is contained in:
parent
3694ef4a2c
commit
0157099576
41
gorm.go
41
gorm.go
|
@ -56,6 +56,26 @@ type Config struct {
|
|||
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
|
||||
type DB struct {
|
||||
*Config
|
||||
|
@ -83,9 +103,16 @@ type Session struct {
|
|||
}
|
||||
|
||||
// Open initialize db session based on dialector
|
||||
func Open(dialector Dialector, config *Config) (db *DB, err error) {
|
||||
if config == nil {
|
||||
config = &Config{}
|
||||
func Open(dialector Dialector, opts ...Option) (db *DB, err error) {
|
||||
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 {
|
||||
|
@ -106,14 +133,6 @@ func Open(dialector Dialector, config *Config) (db *DB, err error) {
|
|||
|
||||
if config.Plugins == nil {
|
||||
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 {
|
||||
|
|
Loading…
Reference in New Issue