Taobin-Recipe-Manager/server/routers/material.go
2023-12-07 09:37:18 +07:00

110 lines
2.7 KiB
Go

package routers
import (
"encoding/json"
"github.com/go-chi/chi/v5"
"go.uber.org/zap"
"net/http"
"recipe-manager/data"
"recipe-manager/models"
"recipe-manager/services/logger"
"strconv"
"strings"
)
type MaterialRouter struct {
data *data.Data
taoLogger *logger.TaoLogger
}
func NewMaterialRouter(data *data.Data, taoLogger *logger.TaoLogger) *MaterialRouter {
return &MaterialRouter{
data: data,
taoLogger: taoLogger,
}
}
func (mr *MaterialRouter) Route(r chi.Router) {
r.Route("/materials", func(r chi.Router) {
r.Get("/code", mr.getMaterialCode)
r.Get("/setting/{mat_id}", mr.getMaterialSettingByMatID)
})
}
func (mr *MaterialRouter) getMaterialCode(w http.ResponseWriter, r *http.Request) {
w.Header().Add("Content-Type", "application/json")
filename := r.URL.Query().Get("filename")
country := r.URL.Query().Get("country")
matIDs := r.URL.Query().Get("mat_ids")
var matIDsUint []uint64
for _, v := range strings.Split(matIDs, ",") {
matIDUint, err := strconv.ParseUint(v, 10, 64)
if err != nil || matIDUint == 0 {
continue
}
matIDsUint = append(matIDsUint, matIDUint)
}
countryID, err := mr.data.GetCountryIDByName(country)
if err != nil {
mr.taoLogger.Log.Error("MaterialRouter.GetMaterialCode", zap.Error(err))
http.Error(w, "Country not found", http.StatusNotFound)
return
}
material := mr.data.GetMaterialCode(matIDsUint, countryID, filename)
if err := json.NewEncoder(w).Encode(material); err != nil {
mr.taoLogger.Log.Error("MaterialRouter.GetMaterialCode", zap.Error(err))
http.Error(w, "Internal Error", http.StatusInternalServerError)
return
}
}
func (mr *MaterialRouter) getMaterialSettingByMatID(w http.ResponseWriter, r *http.Request) {
w.Header().Add("Content-Type", "application/json")
filename := r.URL.Query().Get("filename")
country := r.URL.Query().Get("country")
countryID, err := mr.data.GetCountryIDByName(country)
if err != nil {
mr.taoLogger.Log.Error("MaterialRouter.GetMaterialSettingByMatID", zap.Error(err))
http.Error(w, "Country not found", http.StatusNotFound)
return
}
material := mr.data.GetMaterialSetting(countryID, filename)
matID := chi.URLParam(r, "mat_id")
matIDuint, err := strconv.ParseUint(matID, 10, 64)
if err != nil {
mr.taoLogger.Log.Error("MaterialRouter.GetMaterialSettingByMatID", zap.Error(err))
http.Error(w, "Invalid material id", http.StatusBadRequest)
return
}
var matSetting models.MaterialSetting
for _, mat := range material {
if mat.ID == matIDuint {
matSetting = mat
break
}
}
if err := json.NewEncoder(w).Encode(matSetting); err != nil {
mr.taoLogger.Log.Error("MaterialRouter.GetMaterialSettingByMatID", zap.Error(err))
http.Error(w, "Internal Error", http.StatusInternalServerError)
return
}
}