ketotrack/data/data.go
2024-05-12 17:01:17 -04:00

73 lines
2.4 KiB
Go

// 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"
)
// 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 {
Records []model.Record
dataPath string
}
// 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
}
// 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)
// 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
}
return json.Unmarshal(data, &ctx.Records)
}
// 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)
}
// 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) {
ctx.Records = append(ctx.Records, model.Record{Reading: &reading})
}
// 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) {
ctx.Records = append(ctx.Records, model.Record{Note: &note})
}