ketotrack/data/data.go

58 lines
1.3 KiB
Go
Raw Normal View History

package data
import (
"encoding/json"
"ketotrack/model"
"os"
)
// AppContext is the application data store that holds Records
type AppContext struct {
2024-05-12 20:05:05 +00:00
Records []model.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
func (ctx *AppContext) LoadRecords() error {
data, err := os.ReadFile(ctx.dataPath)
2024-05-12 20:26:05 +00:00
// Create the records file if it does not exist
if os.IsNotExist(err) {
ctx.Records = []model.Record{}
return ctx.SaveRecords()
} else if err != nil {
// Some other type of error has occurred
return err
}
2024-05-12 20:26:05 +00:00
return json.Unmarshal(data, &ctx.Records)
}
// SaveRecords will save records to a file
func (ctx *AppContext) SaveRecords() error {
jsonData, err := json.Marshal(ctx.Records)
if err != nil {
return err
}
return os.WriteFile(ctx.dataPath, jsonData, 0660)
}
// AddReading will add a Reading to the AppContext
func (ctx *AppContext) AddReading(reading model.Reading) {
2024-05-12 20:05:05 +00:00
ctx.Records = append(ctx.Records, model.Record{Reading: &reading})
}
// AddNote will a add a Note to the AppContext
func (ctx *AppContext) AddNote(note model.Note) {
2024-05-12 20:05:05 +00:00
ctx.Records = append(ctx.Records, model.Record{Note: &note})
}