directory/internal/store/store.go

64 lines
1.2 KiB
Go
Raw Normal View History

2024-06-01 22:51:29 +00:00
package store
import (
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
"go.uber.org/fx"
"gorm.io/gorm"
"sneak.berlin/go/directory/internal/config"
"sneak.berlin/go/directory/internal/database"
"sneak.berlin/go/directory/internal/logger"
)
const (
UsersTableName string = "users"
UserAttributesTableName string = "userattributes"
)
type StoreParams struct {
fx.In
Logger *logger.Logger
Config *config.Config
Database *database.Database
}
type Store struct {
db *gorm.DB
logger *logger.Logger
log *zerolog.Logger
params *StoreParams
}
2024-06-15 14:41:37 +00:00
func New(lc fx.Lifecycle, params StoreParams) (*Store, error) {
2024-06-01 22:51:29 +00:00
s := new(Store)
s.logger = params.Logger
s.log = params.Logger.Get()
var err error
s.db, err = params.Database.Get()
if err != nil {
log.Error().Err(err).Msg("failed to get database object")
return nil, err
}
// Auto migrate the schema
err = s.db.AutoMigrate(&User{}, &UserAttribute{})
if err != nil {
log.Error().Err(err).Msg("failed to migrate database schema")
return nil, err
}
return s, nil
}
func (s *Store) Close() {
log.Info().Msg("closing store db")
db, err := s.db.DB()
if err != nil {
log.Error().Err(err).Msg("failed to get generic database object from gorm")
return
}
db.Close()
}