Taobin-Recipe-Manager/server/data/data.go

92 lines
1.6 KiB
Go
Raw Normal View History

2023-09-14 14:52:04 +07:00
package data
import (
"encoding/json"
"log"
"os"
"path/filepath"
2023-09-21 17:28:37 +07:00
"recipe-manager/models"
"sort"
2023-09-14 14:52:04 +07:00
)
func readFile(version string) *models.Recipe {
path := filepath.Join("cofffeemachineConfig", version)
file, err := os.Open(path)
2023-09-14 14:52:04 +07:00
if err != nil {
log.Fatalf("Error when open file: %s", err)
return nil
}
defer file.Close()
2023-09-21 17:28:37 +07:00
var data *models.Recipe
2023-09-14 14:52:04 +07:00
err = json.NewDecoder(file).Decode(&data)
if err != nil {
log.Fatalf("Error when decode file: %s", err)
return nil
}
return data
}
type Data struct {
CurrentVersion string
AllVersions []string
recipe *models.Recipe
2023-09-14 14:52:04 +07:00
}
func NewData() *Data {
files, err := filepath.Glob("cofffeemachineConfig/coffeethai02_*.json")
if err != nil {
log.Panic("Error when scan recipe files:", err)
}
sort.Slice(files, func(i, j int) bool {
file1, err := os.Stat(files[i])
if err != nil {
log.Panic("Error when get file info:", err)
}
file2, err := os.Stat(files[j])
if err != nil {
log.Panic("Error when get file info:", err)
}
return file1.ModTime().After(file2.ModTime())
})
for i := 0; i < len(files); i++ {
files[i] = filepath.Base(files[i])
}
2023-09-14 14:52:04 +07:00
return &Data{
CurrentVersion: "coffeethai02_580.json",
AllVersions: files,
recipe: readFile("coffeethai02_580.json"),
2023-09-14 14:52:04 +07:00
}
}
func (d *Data) GetRecipe(version string) models.Recipe {
if version == "" || version == d.CurrentVersion {
return *d.recipe
}
log.Println("Change recipe to version:", version)
// change current version and read new recipe
d.CurrentVersion = version
d.recipe = readFile(version)
2023-09-25 15:29:42 +07:00
return *d.recipe
2023-09-14 14:52:04 +07:00
}
2023-09-21 17:28:37 +07:00
func (d *Data) GetRecipe01() []models.Recipe01 {
return d.recipe.Recipe01
2023-09-14 14:52:04 +07:00
}