88 lines
2.6 KiB
Go
88 lines
2.6 KiB
Go
package services
|
|
|
|
import (
|
|
"net/http"
|
|
"netina/commands"
|
|
cm "netina/models/commands"
|
|
"netina/queries"
|
|
plan_repository "netina/repositories/plan"
|
|
"netina/validation"
|
|
"strconv"
|
|
|
|
"github.com/labstack/echo/v4"
|
|
)
|
|
|
|
type PlanService struct {
|
|
CommandRepo plan_repository.PlanCommandRepository
|
|
QueryRepo plan_repository.PlanQueryRepository
|
|
}
|
|
|
|
func (s *PlanService) CreatePlan(c echo.Context) error {
|
|
plan := new(cm.CreatePlanCommand)
|
|
if err := c.Bind(plan); err != nil {
|
|
return c.JSON(http.StatusBadRequest, map[string]string{"error": "Invalid request payload"})
|
|
}
|
|
if err := validation.ValidateStruct(plan); err != nil {
|
|
return c.JSON(http.StatusBadRequest, map[string]string{"error": err.Error()})
|
|
}
|
|
|
|
handler := commands.CreatePlanHandler{Repository: s.CommandRepo}
|
|
if err := handler.Handle(*plan); err != nil {
|
|
return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})
|
|
}
|
|
|
|
return c.JSON(http.StatusCreated, plan)
|
|
}
|
|
|
|
func (s *PlanService) GetPlan(c echo.Context) error {
|
|
id, err := strconv.Atoi(c.Param("id"))
|
|
if err != nil {
|
|
return c.JSON(http.StatusBadRequest, map[string]string{"error": "Invalid plan ID"})
|
|
}
|
|
|
|
handler := queries.GetPlanHandler{Repository: s.QueryRepo}
|
|
plan, err := handler.Handle(uint(id))
|
|
if err != nil {
|
|
return c.JSON(http.StatusNotFound, map[string]string{"error": err.Error()})
|
|
}
|
|
|
|
return c.JSON(http.StatusOK, plan)
|
|
}
|
|
|
|
func (s *PlanService) UpdatePlan(c echo.Context) error {
|
|
id, err := strconv.Atoi(c.Param("id"))
|
|
if err != nil {
|
|
return c.JSON(http.StatusBadRequest, map[string]string{"error": "Invalid plan ID"})
|
|
}
|
|
|
|
plan := new(cm.UpdatePlanCommand)
|
|
if err := c.Bind(plan); err != nil {
|
|
return c.JSON(http.StatusBadRequest, map[string]string{"error": "Invalid request payload"})
|
|
}
|
|
if err := validation.ValidateStruct(plan); err != nil {
|
|
return c.JSON(http.StatusBadRequest, map[string]string{"error": err.Error()})
|
|
}
|
|
|
|
handler := commands.UpdatePlanHandler{Repository: s.CommandRepo}
|
|
updatedPlan, err := handler.Handle(uint(id), *plan)
|
|
if err != nil {
|
|
return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})
|
|
}
|
|
|
|
return c.JSON(http.StatusOK, updatedPlan)
|
|
}
|
|
|
|
func (s *PlanService) RemovePlan(c echo.Context) error {
|
|
id, err := strconv.Atoi(c.Param("id"))
|
|
if err != nil {
|
|
return c.JSON(http.StatusBadRequest, map[string]string{"error": "Invalid plan ID"})
|
|
}
|
|
|
|
handler := commands.RemovePlanHandler{Repository: s.CommandRepo}
|
|
if err := handler.Handle(uint(id)); err != nil {
|
|
return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})
|
|
}
|
|
|
|
return c.NoContent(http.StatusNoContent)
|
|
}
|