-
-
Notifications
You must be signed in to change notification settings - Fork 97
/
gorm.go
51 lines (47 loc) · 1003 Bytes
/
gorm.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
package database
import (
"database/sql"
"github.com/bitmagnet-io/bitmagnet/internal/boilerplate/lazy"
"github.com/bitmagnet-io/bitmagnet/internal/database/logger"
"go.uber.org/fx"
"go.uber.org/zap"
"gorm.io/driver/postgres"
"gorm.io/gorm"
gormlogger "gorm.io/gorm/logger"
"time"
)
type Params struct {
fx.In
SqlDB lazy.Lazy[*sql.DB]
Logger *zap.SugaredLogger
}
type Result struct {
fx.Out
GormDb lazy.Lazy[*gorm.DB]
}
func New(p Params) Result {
return Result{
GormDb: lazy.New(func() (*gorm.DB, error) {
sqlDB, err := p.SqlDB.Get()
if err != nil {
return nil, err
}
dialector := postgres.New(postgres.Config{
Conn: sqlDB,
})
gDb, dbErr := gorm.Open(dialector, &gorm.Config{
Logger: logger.New(logger.Params{
ZapLogger: p.Logger,
Config: logger.Config{
LogLevel: gormlogger.Info,
SlowThreshold: time.Second * 3,
},
}).GormLogger,
})
if dbErr != nil {
return nil, dbErr
}
return gDb, nil
}),
}
}