refactor records to implement AppConfig

This commit is contained in:
agatha 2024-05-12 15:53:57 -04:00
parent 0ca262c2ea
commit 1874a875f5

View File

@ -14,12 +14,22 @@ type Record struct {
// AppContext is the application data store that holds Records
type AppContext struct {
Records []Record
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
}
// LoadRecords will load records from file
func (ctx *AppContext) LoadRecords(filename string) error {
data, err := os.ReadFile(filename)
func (ctx *AppContext) LoadRecords() error {
data, err := os.ReadFile(ctx.dataPath)
if err != nil {
return err
}
@ -27,12 +37,12 @@ func (ctx *AppContext) LoadRecords(filename string) error {
}
// SaveRecords will save records to a file
func (ctx *AppContext) SaveRecords(filename string) error {
func (ctx *AppContext) SaveRecords() error {
jsonData, err := json.Marshal(ctx.Records)
if err != nil {
return err
}
return os.WriteFile(filename, jsonData, 0660)
return os.WriteFile(ctx.dataPath, jsonData, 0660)
}
// AddReading will add a Reading to the AppContext