add file select for multiple country
This commit is contained in:
parent
e5eee656d5
commit
652ecbbf1f
9 changed files with 294 additions and 47 deletions
101
server/helpers/filereader.go
Normal file
101
server/helpers/filereader.go
Normal file
|
|
@ -0,0 +1,101 @@
|
|||
package helpers
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"log"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"recipe-manager/models"
|
||||
"sort"
|
||||
)
|
||||
|
||||
func ListFile(rootPath string) []string {
|
||||
files, err := filepath.Glob(rootPath)
|
||||
if err != nil {
|
||||
log.Panic("Error when scan recipe files:", err)
|
||||
}
|
||||
return files
|
||||
}
|
||||
|
||||
func ReadFile(filePath string) (string, error) {
|
||||
file, err := os.ReadFile(filePath)
|
||||
|
||||
if err != nil {
|
||||
log.Fatalf("Error when open file: %s", err)
|
||||
return "", err
|
||||
}
|
||||
|
||||
return string(file), nil
|
||||
}
|
||||
|
||||
func ReadRecipeFile(filePath string) models.Recipe {
|
||||
file, err := os.Open(filePath)
|
||||
|
||||
if err != nil {
|
||||
log.Fatalf("Error when open file: %s", err)
|
||||
return models.Recipe{}
|
||||
}
|
||||
|
||||
defer file.Close()
|
||||
|
||||
var data models.Recipe
|
||||
|
||||
err = json.NewDecoder(file).Decode(&data)
|
||||
|
||||
if err != nil {
|
||||
log.Fatalf("Error when decode file: %s", err)
|
||||
return models.Recipe{}
|
||||
}
|
||||
|
||||
return data
|
||||
}
|
||||
|
||||
type RecipePath struct {
|
||||
Name string `json:"name"`
|
||||
Path string `json:"path"`
|
||||
}
|
||||
|
||||
type CountryName struct {
|
||||
CountryID string `json:"countryId"`
|
||||
CountryName string `json:"countryName"`
|
||||
}
|
||||
|
||||
func ScanRecipeFiles(countries []CountryName) map[string][]RecipePath {
|
||||
recipeFiles := map[string][]RecipePath{}
|
||||
|
||||
for _, country := range countries {
|
||||
var files []string
|
||||
if country.CountryID == "thai" {
|
||||
files = ListFile("cofffeemachineConfig/coffeethai02_*.json")
|
||||
} else {
|
||||
files = ListFile("cofffeemachineConfig/" + country.CountryID + "/coffeethai02_*.json")
|
||||
}
|
||||
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++ {
|
||||
if _, ok := recipeFiles[country.CountryID]; !ok {
|
||||
recipeFiles[country.CountryID] = []RecipePath{}
|
||||
}
|
||||
|
||||
recipeFiles[country.CountryID] = append(recipeFiles[country.CountryID], RecipePath{
|
||||
Name: filepath.Base(files[i]),
|
||||
Path: files[i],
|
||||
})
|
||||
}
|
||||
}
|
||||
return recipeFiles
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue