2024-05-12 19:45:19 +00:00
|
|
|
package data
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/json"
|
|
|
|
"ketotrack/model"
|
|
|
|
"os"
|
|
|
|
)
|
|
|
|
|
|
|
|
// Record holds a pointer to a Reading or Note.
|
|
|
|
type Record struct {
|
|
|
|
Reading *model.Reading `json:"reading,omitempty"`
|
|
|
|
Note *model.Note `json:"note,omitempty"`
|
|
|
|
}
|
|
|
|
|
|
|
|
// AppContext is the application data store that holds Records
|
|
|
|
type AppContext struct {
|
2024-05-12 19:53:57 +00:00
|
|
|
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
|
2024-05-12 19:45:19 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// LoadRecords will load records from file
|
2024-05-12 19:53:57 +00:00
|
|
|
func (ctx *AppContext) LoadRecords() error {
|
|
|
|
data, err := os.ReadFile(ctx.dataPath)
|
2024-05-12 19:45:19 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
return json.Unmarshal(data, &ctx.Records)
|
|
|
|
}
|
|
|
|
|
|
|
|
// SaveRecords will save records to a file
|
2024-05-12 19:53:57 +00:00
|
|
|
func (ctx *AppContext) SaveRecords() error {
|
2024-05-12 19:45:19 +00:00
|
|
|
jsonData, err := json.Marshal(ctx.Records)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2024-05-12 19:53:57 +00:00
|
|
|
return os.WriteFile(ctx.dataPath, jsonData, 0660)
|
2024-05-12 19:45:19 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// AddReading will add a Reading to the AppContext
|
|
|
|
func (ctx *AppContext) AddReading(reading model.Reading) {
|
|
|
|
ctx.Records = append(ctx.Records, Record{Reading: &reading})
|
|
|
|
}
|
|
|
|
|
|
|
|
// AddNote will a add a Note to the AppContext
|
|
|
|
func (ctx *AppContext) AddNote(note model.Note) {
|
|
|
|
ctx.Records = append(ctx.Records, Record{Note: ¬e})
|
|
|
|
}
|