-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmodule.go
98 lines (82 loc) · 2.08 KB
/
module.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
package sqlorm
import (
"fmt"
"github.com/tinh-tinh/tinhtinh/common"
"github.com/tinh-tinh/tinhtinh/core"
"gorm.io/gorm"
)
type Options struct {
Dialect gorm.Dialector
Factory func(module *core.DynamicModule) gorm.Dialector
Models []interface{}
}
const ConnectDB core.Provide = "ConnectDB"
func ForRoot(opt Options, configs ...gorm.Option) core.Module {
return func(module *core.DynamicModule) *core.DynamicModule {
var dialector gorm.Dialector
if opt.Factory != nil {
dialector = opt.Factory(module)
} else {
dialector = opt.Dialect
}
conn, err := gorm.Open(dialector, configs...)
if err != nil {
panic(err)
}
conn.Exec("CREATE EXTENSION IF NOT EXISTS \"uuid-ossp\";")
fmt.Println("connected to database")
err = conn.AutoMigrate(opt.Models...)
if err != nil {
panic(err)
}
fmt.Println("Migrated successful")
sqlModule := module.New(core.NewModuleOptions{})
sqlModule.NewProvider(core.ProviderOptions{
Name: ConnectDB,
Value: conn,
})
sqlModule.Export(ConnectDB)
return sqlModule
}
}
func Inject(module *core.DynamicModule) *gorm.DB {
db, ok := module.Ref(ConnectDB).(*gorm.DB)
if !ok {
return nil
}
return db
}
func InjectRepository[M any](module *core.DynamicModule) *Repository[M] {
var model M
modelName := core.Provide(fmt.Sprintf("%sRepo", common.GetStructName(model)))
data, ok := module.Ref(modelName).(*Repository[M])
fmt.Println(data)
if !ok {
return nil
}
return data
}
func ForFeature(val ...RepoCommon) core.Module {
return func(module *core.DynamicModule) *core.DynamicModule {
modelModule := module.New(core.NewModuleOptions{})
for _, v := range val {
name := GetRepoName(v.GetName())
modelModule.NewProvider(core.ProviderOptions{
Name: name,
Factory: func(param ...interface{}) interface{} {
connect := param[0].(*gorm.DB)
if connect != nil {
v.SetDB(connect)
}
return v
},
Inject: []core.Provide{ConnectDB},
})
modelModule.Export(name)
}
return modelModule
}
}
func GetRepoName(name string) core.Provide {
return core.Provide(fmt.Sprintf("%sRepo", name))
}