ketotrack/data/data.go

73 lines
2.4 KiB
Go
Raw Permalink Normal View History

2024-05-12 21:01:17 +00:00
// Package data manages the loading, saving, and manipulation of application data
// pertaining to health tracking. It provides an abstraction layer over the storage
// mechanism used for persisting records and offers convenient methods to interact
// with the data.
package data
import (
"encoding/json"
"ketotrack/model"
"os"
)
2024-05-12 21:01:17 +00:00
// AppContext represents the application's data context, encapsulating the storage
// and management of health-related records. It provides mechanisms to load and save
// these records from a persistent storage.
type AppContext struct {
2024-05-12 20:05:05 +00:00
Records []model.Record
dataPath string
}
2024-05-12 21:01:17 +00:00
// NewContext initializes a new application data context with the specified data
// path. It attempts to load existing records from the provided data path, or
// initializes an empty context if the records do not exist.
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 21:01:17 +00:00
// LoadRecords loads the records from the data file specified in the AppContext.
// If the records file does not exist, it initializes an empty record list and
// saves it to create the 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)
}
2024-05-12 21:01:17 +00:00
// SaveRecords serializes the current records to JSON and writes them to the
// data path specified in the AppContext. It ensures data persistence with
// appropriate access permissions.
func (ctx *AppContext) SaveRecords() error {
jsonData, err := json.Marshal(ctx.Records)
if err != nil {
return err
}
return os.WriteFile(ctx.dataPath, jsonData, 0660)
}
2024-05-12 21:01:17 +00:00
// AddReading appends a new Reading record to the AppContext. It updates the
// application context's records with the latest readings data.
func (ctx *AppContext) AddReading(reading model.Reading) {
2024-05-12 20:05:05 +00:00
ctx.Records = append(ctx.Records, model.Record{Reading: &reading})
}
2024-05-12 21:01:17 +00:00
// AddNote appends a new Note record to the AppContext. It updates the
// application context's records with the newly added note.
func (ctx *AppContext) AddNote(note model.Note) {
2024-05-12 20:05:05 +00:00
ctx.Records = append(ctx.Records, model.Record{Note: &note})
}