Add db module

This commit is contained in:
2026-03-08 11:56:57 +03:00
parent 056e2ad529
commit e56b1f1305
7 changed files with 135 additions and 3 deletions

View File

@@ -2,11 +2,13 @@ package config
import (
logging "payouts/internal/log/config"
database "payouts/internal/service/database/config"
monitoring "payouts/internal/service/monitoring/config"
)
type App struct {
Server Server
Metrics monitoring.Metrics
Log logging.Log
Server Server
Metrics monitoring.Metrics
Database database.Database
Log logging.Log
}

View File

@@ -0,0 +1,7 @@
package config
type Database struct {
Type string
Connection string
LogLevel string
}

View File

@@ -0,0 +1,44 @@
package database
import (
"errors"
slogGorm "github.com/orandin/slog-gorm"
"gorm.io/driver/postgres"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
)
type dbService struct {
dbType string
db *gorm.DB
}
func NewDatabaseService(dbType, connection, logLevel string) (DatabaseService, error) {
var dialector gorm.Dialector
switch dbType {
case "sqlite":
dialector = sqlite.Open(connection)
case "postgres":
dialector = postgres.Open(connection)
default:
return nil, errors.New("unknown dbType")
}
db, err := gorm.Open(dialector, &gorm.Config{
Logger: slogGorm.New(),
})
if err == nil {
db.DB()
db.AutoMigrate()
// db.LogMode(true)
}
result := &dbService{}
result.dbType = dbType
result.db = db
return result, err
}

View File

@@ -0,0 +1,26 @@
package database
import (
"payouts/internal/config"
"go.uber.org/fx"
)
var Module = fx.Options(
fx.Provide(New),
)
type DatabaseService interface {
}
// Params represents the module input params
type Params struct {
fx.In
AppConfig *config.App
}
// NewPersistence instantiates the persistence module
func New(p Params) (DatabaseService, error) {
return NewDatabaseService(p.AppConfig.Database.Type, p.AppConfig.Database.Connection, p.AppConfig.Database.LogLevel)
}