chore: reorder part two
This commit is contained in:
@@ -0,0 +1,61 @@
|
||||
package database
|
||||
|
||||
import (
|
||||
"orbits-server/internal/server/bootstrap"
|
||||
"path/filepath"
|
||||
"time"
|
||||
|
||||
"gorm.io/driver/sqlite"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/logger"
|
||||
)
|
||||
|
||||
//var watchdogStop = make(chan struct{})
|
||||
|
||||
func KickoffDatabase(workDir string) (*gorm.DB, error) {
|
||||
dbLoc := filepath.Join(workDir, "station.db")
|
||||
db, err := gorm.Open(sqlite.Open(dbLoc), &gorm.Config{
|
||||
Logger: logger.Discard, // disable gorm logging since its not slog (yet)
|
||||
TranslateError: true,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// try to use GORM automigrate if the schema changes
|
||||
if err := db.AutoMigrate(
|
||||
&Command{},
|
||||
&Device{},
|
||||
&File{},
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// create the first row if it does not exist yet
|
||||
if err := db.FirstOrCreate(&Command{}, Command{
|
||||
ID: 0,
|
||||
State: "idle",
|
||||
MediaType: Unspecified,
|
||||
}).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return db, nil
|
||||
}
|
||||
|
||||
func KickoffDatabaseWatchdog(env bootstrap.Environment, db *gorm.DB) {
|
||||
timeInterval := time.Second * time.Duration(env.WatchdogInterval)
|
||||
ticker := time.NewTicker(timeInterval)
|
||||
|
||||
go func() {
|
||||
defer ticker.Stop()
|
||||
|
||||
// run the watchdog function once to see if all is well.
|
||||
watchdog(env, db)
|
||||
// then defer to a decoupled/disowned golang goroutine
|
||||
|
||||
for range ticker.C {
|
||||
watchdog(env, db)
|
||||
}
|
||||
}()
|
||||
}
|
||||
Reference in New Issue
Block a user