Compare commits

...

2 Commits

Author SHA1 Message Date
796075d9f2 implement AppConfig and refactored AppContext 2024-05-12 15:54:36 -04:00
1874a875f5 refactor records to implement AppConfig 2024-05-12 15:53:57 -04:00
2 changed files with 24 additions and 8 deletions

View File

@ -14,12 +14,22 @@ type Record struct {
// AppContext is the application data store that holds Records // AppContext is the application data store that holds Records
type AppContext struct { type AppContext struct {
Records []Record Records []Record
dataPath string
}
func NewContext(dataPath string) (AppContext, error) {
ctx := AppContext{dataPath: dataPath}
err := ctx.LoadRecords()
if err != nil {
return AppContext{}, err
}
return ctx, nil
} }
// LoadRecords will load records from file // LoadRecords will load records from file
func (ctx *AppContext) LoadRecords(filename string) error { func (ctx *AppContext) LoadRecords() error {
data, err := os.ReadFile(filename) data, err := os.ReadFile(ctx.dataPath)
if err != nil { if err != nil {
return err return err
} }
@ -27,12 +37,12 @@ func (ctx *AppContext) LoadRecords(filename string) error {
} }
// SaveRecords will save records to a file // SaveRecords will save records to a file
func (ctx *AppContext) SaveRecords(filename string) error { func (ctx *AppContext) SaveRecords() error {
jsonData, err := json.Marshal(ctx.Records) jsonData, err := json.Marshal(ctx.Records)
if err != nil { if err != nil {
return err return err
} }
return os.WriteFile(filename, jsonData, 0660) return os.WriteFile(ctx.dataPath, jsonData, 0660)
} }
// AddReading will add a Reading to the AppContext // AddReading will add a Reading to the AppContext

12
main.go
View File

@ -9,6 +9,7 @@ import (
"strconv" "strconv"
"strings" "strings"
"ketotrack/config"
"ketotrack/data" "ketotrack/data"
"ketotrack/model" "ketotrack/model"
) )
@ -38,9 +39,14 @@ func init() {
} }
func main() { func main() {
var appCtx data.AppContext appConfig := config.Load()
appCtx, err := data.NewContext(appConfig.DataPath)
if err != nil {
fmt.Printf("Error initializing application context: %s\n", err)
return
}
if err := appCtx.LoadRecords(recordsFilename); err != nil { if err := appCtx.LoadRecords(); err != nil {
fmt.Printf("Error loading records from file: %s\n", err) fmt.Printf("Error loading records from file: %s\n", err)
} }
@ -79,7 +85,7 @@ func main() {
} }
// Save Records before exiting // Save Records before exiting
if err := appCtx.SaveRecords(recordsFilename); err != nil { if err := appCtx.SaveRecords(); err != nil {
fmt.Printf("Error saving records to file: %s\n", err) fmt.Printf("Error saving records to file: %s\n", err)
} }
} }