update recipe viewer

This commit is contained in:
Kenta420 2024-02-27 13:43:26 +07:00
parent cf5b11b267
commit a12121fca6
19 changed files with 677 additions and 363 deletions

View file

@ -2,10 +2,15 @@ package v2
import (
"encoding/json"
"fmt"
"net/http"
"os"
"path"
"recipe-manager/data"
"recipe-manager/models"
modelsV2 "recipe-manager/models/v2"
"recipe-manager/services/logger"
"time"
"github.com/go-chi/chi/v5"
)
@ -65,5 +70,51 @@ func (rr *recipeRouter) Route(r chi.Router) {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
})
r.Post("/", func(w http.ResponseWriter, r *http.Request) {
w.Header().Add("Content-Type", "application/json")
var recipe models.Recipe
if err := json.NewDecoder(r.Body).Decode(&recipe); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
countryID := r.URL.Query().Get("country_id")
filename := fmt.Sprintf("coffeethai02_%d_%s.json", recipe.MachineSetting.ConfigNumber, time.Now().Format("2-1-2006_15-04-05"))
// TODO: validate recipe data
// recipeID, err := rr.data.CreateRecipe(recipe)
// if err != nil {
// http.Error(w, err.Error(), http.StatusInternalServerError)
// return
// }
// write file to disk
recipePath := path.Join("./cofffeemachineConfig", countryID, filename)
_, err := os.Stat(recipePath)
if os.IsNotExist(err) {
file, err := os.Create(recipePath)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
defer file.Close()
encoder := json.NewEncoder(file)
encoder.SetIndent("", " ")
if err := encoder.Encode(recipe); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
} else {
http.Error(w, "File already exists", http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusCreated)
})
})
}