refactor records to implement AppConfig
This commit is contained in:
parent
0ca262c2ea
commit
1874a875f5
@ -14,12 +14,22 @@ type Record struct {
|
|||||||
|
|
||||||
// AppContext is the application data store that holds Records
|
// AppContext is the application data store that holds Records
|
||||||
type AppContext struct {
|
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
|
// LoadRecords will load records from file
|
||||||
func (ctx *AppContext) LoadRecords(filename string) error {
|
func (ctx *AppContext) LoadRecords() error {
|
||||||
data, err := os.ReadFile(filename)
|
data, err := os.ReadFile(ctx.dataPath)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@ -27,12 +37,12 @@ func (ctx *AppContext) LoadRecords(filename string) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// SaveRecords will save records to a file
|
// 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)
|
jsonData, err := json.Marshal(ctx.Records)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
return os.WriteFile(filename, jsonData, 0660)
|
return os.WriteFile(ctx.dataPath, jsonData, 0660)
|
||||||
}
|
}
|
||||||
|
|
||||||
// AddReading will add a Reading to the AppContext
|
// AddReading will add a Reading to the AppContext
|
||||||
|
Loading…
Reference in New Issue
Block a user