package http
import (
- serrors "errors"
shttp "net/http"
- "strconv"
- "jsdaj.tq/pf/internal/errors"
"jsdaj.tq/pf/pkg/core"
"jsdaj.tq/pf/pkg/http/util"
)
}
func (s *Server) ingredientHandleUpdate(w shttp.ResponseWriter, r *shttp.Request) {
- id, err := strconv.Atoi(r.PathValue("id"))
+ id, err := util.ParseParamIdAndErr(w, r)
if err != nil {
- util.HandleServiceError(w, errors.MapError(serrors.New("bad_id")))
return
}
}
func (s *Server) ingredientHandleDelete(w shttp.ResponseWriter, r *shttp.Request) {
- id, err := strconv.Atoi(r.PathValue("id"))
+ id, err := util.ParseParamIdAndErr(w, r)
if err != nil {
- util.HandleServiceError(w, errors.MapError(serrors.New("bad_id")))
return
}
util.ParseAndWriteResponse(w, struct{}{}, shttp.StatusNoContent)
}
-func (s *Server) ingredientHandleGet(w shttp.ResponseWriter, r *shttp.Request) {}
+func (s *Server) ingredientHandleGet(w shttp.ResponseWriter, r *shttp.Request) {
+ id, err := util.ParseParamIdAndErr(w, r)
+ if err != nil {
+ return
+ }
+
+ in, err := s.ingredients.Get(id)
+ if err != nil {
+ util.HandleServiceError(w, err)
+ return
+ }
+
+ util.ParseAndWriteResponse(w, in, shttp.StatusOK)
+}
func (s *Server) ingredientHandleList(w shttp.ResponseWriter, r *shttp.Request) {
ingredients, err := s.ingredients.List()
"encoding/json"
"log"
"net/http"
+ "strconv"
+ serrors "errors"
+
+ "jsdaj.tq/pf/internal/errors"
)
+func ParseParamIdAndErr(w http.ResponseWriter, r *http.Request) (int, error) {
+ id, err := strconv.Atoi(r.PathValue("id"))
+ if err != nil {
+ HandleServiceError(w, errors.MapError(serrors.New("bad_id")))
+ return 0, err
+ }
+ return id, nil
+}
+
func ParseRequestAndErr[T any](w http.ResponseWriter, r *http.Request, input T) error {
err := json.NewDecoder(r.Body).Decode(input)
if err != nil {
return err
}
+func (s *Ingredient) Get(id int) (*core.Ingredient, error) {
+ in, err := s.repository.IngredientGet(id)
+ if err != nil {
+ return nil, errors.MapError(err)
+ }
+
+ if in == nil {
+ return nil, errors.Error{Code: errors.NotFoundError, Message: "not_found"}
+ }
+
+ return in, nil
+}
+
func InitIngredientService(repository persistence.IngredientRepository) Ingredient {
return Ingredient{
repository,