From 3ae5ea780ef9c90c54da18148f666d0c3bced95e Mon Sep 17 00:00:00 2001 From: agatha Date: Sun, 12 May 2024 15:45:19 -0400 Subject: [PATCH] data package handles AppContext and Records --- data/records.go | 46 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 data/records.go diff --git a/data/records.go b/data/records.go new file mode 100644 index 0000000..91e05bc --- /dev/null +++ b/data/records.go @@ -0,0 +1,46 @@ +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 { + Records []Record +} + +// LoadRecords will load records from file +func (ctx *AppContext) LoadRecords(filename string) error { + data, err := os.ReadFile(filename) + if err != nil { + return err + } + return json.Unmarshal(data, &ctx.Records) +} + +// SaveRecords will save records to a file +func (ctx *AppContext) SaveRecords(filename string) error { + jsonData, err := json.Marshal(ctx.Records) + if err != nil { + return err + } + return os.WriteFile(filename, jsonData, 0660) +} + +// 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}) +}